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.
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.