0

This question already has an answer here


I am searching for some way to replace highlighted text that is inside a text area with a new string that has already been defined.

I can get everything in the text area with:

var all_text = document.activeElement.value;

and I can get the highlighted text with:

var selected_text = window.getSelection().toString();

But how can I replace the selected text with a new string?

I have seen many related questions on this site, but every solution I have seen so far just says to use str.replace().

I do not want to simply use str.replace()because if there are multiple instances of selected_text contained within the text area, it can result undesirable behavior.

enter image description here

I need to supplement the function with additional test conditions to ensure that only the selected text gets replaced and not some other string that happened to be equivalent to its toString() value.

I thought I could make use of the anchorOffest property of selection objects, but the property doesn't seem to work in chrome. In fact most of the selection properties don't seem to be working.

Community
  • 1
  • 1
Luke
  • 5,567
  • 4
  • 37
  • 66

1 Answers1

0

if selected_text has a local scope, you really don't have to worry about
creating multiple instances because js garbage collector will do the job.
If selected_text has a global scope, it is a singleton.
But.. if you are really really concern about creating multiple instances,
just save your value to the text tag attribute
I am not sure how ur code is working but below is my suggestion.

var text = document.getElementById("text");
text.setAttribute("selected_text", false);
text.addEventListener("keyup", function(){
    var all_text = document.activeElement.value;
    this.setAttribute("selected_text", window.getSelection().toString());
    //if you need to send highlighted value
    var txt = this.getAttribute("selected_text");
    sendHightlightedTxt(txt);
});
Seho Lee
  • 4,048
  • 9
  • 32
  • 42