Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery replace marked text

I am trying to replace specific highlighted(marked) text from element.

This is how I get the highlighted 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 textarea: "apple banana apple orange" and mark the third word (apple) I want to replace exactly what I have marked without any other occurrences of "apple" in the textarea.

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

like image 926
Zhivko Avatar asked Jul 09 '12 16:07

Zhivko


People also ask

How to replace a word in word in jQuery?

$("#notice p"). text($("#notice p"). text(). replace("some", "My"));

How to change text in a div with jQuery?

To replace only text inside a div using jQuery, use the text() method.

How to change inner text in jQuery?

In JavaScript, the "inner" text of an HTML element refers to the text between any set of HTML tags and using innerText property, one can set the text in JavaScript. But to set innerText using jQuery, use text() method. jQuery text() method sets the innerText of any element.


2 Answers

You could 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'd play with this a little it might be off by 1 on either the startStr or endStr (I always mess that up :/ ) but this should do what you're looking to do.

like image 125
Dan Avatar answered Sep 22 '22 02:09

Dan


Wrote this before the above answer, but I'll keep it because it is just a different way of writing the code/doesn't 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");
like image 29
bokonic Avatar answered Sep 20 '22 02:09

bokonic