Put a tags round user highlighted text?
<p>I need to get the user selected area of a textarea and then insert <code>&lt;a&gt;</code> tags round it.</p>

<p>I use this to get the user selected area:</p>

<pre><code>var textComponent = document.getElementById('article');
var selectedText;

if (document.selection != undefined)
{
    textComponent.focus();
    var sel = document.selection.createRange();
    selectedText = sel.text;
}

// Mozilla version
else if (textComponent.selectionStart != undefined)
{
    var startPos = textComponent.selectionStart;
    var endPos = textComponent.selectionEnd;
    selectedText = textComponent.value.substring(startPos, endPos)
}
</code></pre>

<p>Now, I know I can do a string search for the user selected text and insert a tags round it, but what happens if that user selected text appears twice in the text, for example.</p>

<blockquote>
  <p>Hello to you, goodbye to you.</p>
</blockquote>

<p>If the user highlights the second 'you' for the link they want, surely a string replace would put a tags around every instance of 'you'.</p>

<p>Whats the best way to do this?</p>
