Get the selected string with position from textarea although it exists multiple times

140
February 20, 2021, at 8:30 PM

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?

Answer 1

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>

Rent Charter Buses Company
READ ALSO
Get time difference between two tables only for rows with the same &#39;id&#39; - MySQL

Get time difference between two tables only for rows with the same 'id' - MySQL

I ned to ged time difference between tableA and tableB for rows with the same idTherefore id 10 and 11

125
Laravel MongoDB cannot get belongsTo relationship properly value

Laravel MongoDB cannot get belongsTo relationship properly value

When using jenssegers/laravel-mongodb, the belongsTo relationship properly always returns null, despite, when dumping, the value appearingHow can I get the belongsTo relationship?

180
Jetpack Paging 3 inside java/kotlin module

Jetpack Paging 3 inside java/kotlin module

I'm developing an app with clean architecture principlesI've a domain module which is a Java/Kotlin module and it hasn't android dependencies and a domainImpl module which is an Android module and has dependencies to local, remote and domain module

146
How to set a delay in Postam Runner using a csv file as input

How to set a delay in Postam Runner using a csv file as input

I'm using postman to test an API which is as follows: (this is a POST)

161