Finding indices of highlighted text
<p>I'm trying to save information about text that a user has highlighted in a webpage.  Currently I'm using the getSelection method shown below:</p>

<pre><code> var txt = '';
 if (window.getSelection){txt = window.getSelection();}
 else if (document.getSelection){txt = document.getSelection();}
 else if (document.selection){txt = document.selection.createRange().text;}
 else return;
</code></pre>

<p>to retrieve the highlighted text. Then I'm searching through the entire text body and storing the indices of the highlighted text. The getSelection method only returns what text is highlighted so the problem is that if the highlighted text appears multiple times in the text body, the search could find the wrong repeat of the text and thus save the wrong indices.</p>

<p>Any ideas how to ensure that I'm saving the right indices?</p>

<p>Thanks!</p>
