function addURL(e) {
var n = document.selection ? document.selection.createRange().text : e.value.substring(e.selectionStart, e.selectionEnd);
var a = n + '[link]';
e.value = e.value.replace(n, a);
}
<input type="button" value="Add URL" onclick="addURL(text)">
<br><br>
<textarea id="text">This is a test. This is a test. This is a test.</textarea>
Please run my code snippet. Select/activate/highlight any word/string in the textarea and press the Add link
button.
If you e.g. select test
in the textarea and press the Add link
button, it'll append [link]
to test
.
This is working very well, but only if there's only one test
in the text area: Try the same again with the test
in the second sentence. You'll see, the [link]
will get added to the first test
in the textarea instead of to the selected one.
How can I fix that?