I need to get the user selected area of a textarea and then insert <a> tags round it.
I use this to get the user selected area:
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)
}
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.
Hello to you, goodbye to you.
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’.
Whats the best way to do this?
You could use my jQuery plug-in for this (demo):
Alternatively you could use the
getInputSelection()function that I’ve posted on Stack Overflow a few times to get the selection start and end character indices in all major browsers and then do string substitution on the textarea’svalue: