6

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?

ayyp
  • 6,590
  • 4
  • 33
  • 47
Zhivko
  • 550
  • 4
  • 16

2 Answers2

5

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.

Dan
  • 2,625
  • 7
  • 39
  • 52
3

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");
bokonic
  • 1,751
  • 10
  • 12
  • personally think your answer was better then mine. Much cleaner and as a function it can be managed easier. gj – Dan Jul 09 '12 at 17:30