0

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?

David
  • 2,898
  • 3
  • 21
  • 57
  • Where do you want the link to go? At the moment it seems to be going to the start of the textarea. Do you want it to go just before the word or phrase that the user has highlighted? – A Haworth Feb 20 '21 at 09:02
  • @AHaworth I want `[link]` to go just after the highlighted string. Isn't this working for you? Are you sure this goes to the start of the textarea for you? – David Feb 20 '21 at 09:13
  • Ah, I was pointing at rather than selecting, yes it's OK. – A Haworth Feb 20 '21 at 09:30

1 Answers1

2

That is because your using replace which will replace only the first instance of all the matched value. You need to use substring

function addURL(e) {
  var n = window.selection ? window.selection.createRange().text : e.value.substring(e.selectionStart, e.selectionEnd);
  var a = n + '[link]';
  e.value = e.value.substring(0, e.selectionStart) + a + e.value.substring(e.selectionEnd, e.value.length);
}
#text {
  width: 150px;
  height: 50px;
}
<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>
brk
  • 48,835
  • 10
  • 56
  • 78