Replacing the nth location of the selected text using jQuery
<p>I've the following div:</p>

<pre><code>&lt;div id="target" &gt;hello(first), hello(second), hello(third), hello(fourth)&lt;/div&gt;
</code></pre>

<p>and following code based on this <a href="http://stackoverflow.com/questions/5765381/how-do-i-wrap-a-text-selection-from-window-getselection-getrangeat0-with-an-h">discussion</a>:</p>

<pre><code>    $(document).ready(function(){
      $('#target').bind('mouseup', function(){
           var needle = window
            .getSelection()
            .getRangeAt(0);
           var haystack = $(this).text();
           var newText = haystack.replace(needle,'&lt;span class="highlight"&gt;' + needle + '&lt;/span&gt;');
           $(this).html(newText);             
      });   
</code></pre>

<p>When I select one of the "hello", it 'randomly' highlights one of them rather than the actual selected "hello".</p>

<p>How can I highlight the selected one?</p>

<p>Thanks in advance for your help.</p>
