JQuery replace selected text

I am trying to replace the selected selected (marked) text from an element.

Here's how I got the selected text so far:

var markArea = $('.ElementText textarea').get(0); var text = markArea.value.substring(markArea.selectionStart, markArea.selectionEnd); 

So, if I have something like this in the text box: “apple banana apple orange” and mark the third word (apple), I want to exactly replace what I have indicated, without any other cases of “apple” in the text box .

Is there a way to specify the start and end areas where the code should look for a replacement in the string?

+6
source share
2 answers

You can try something like this,

 var markArea = $('.ElementText textarea').get(0); var startStr = markArea.value.substring(0,markArea.selectionStart); var endStr = markArea.value.substring(markArea.selectionEnd); var text = startStr +"REPLACEMENT VALUE HERE"+ endStr; $('.ElementText textarea').val(text); 

I would play with this a bit, it could be disabled by 1 on startStr or endStr (I always messed up this: /), but that should do what you want to do.

+5
source

Wrote this before the above answer, but I will save it because it is just another way of writing code / does not use jQuery:

 function replaceAtIndex(str,s,e,rep){ return str.slice(0,s) + rep + str.slice(e); } markArea.value = replaceAtIndex(markArea.value,markArea.selectionStart,markArea.selectionEnd,"replacement"); 
+3
source

Source: https://habr.com/ru/post/920053/


All Articles