I have been looking high and low for an answer but failed.
Is there a cross-browser solution to replace selected text in contenteditable div?
I simply want users to highlight some text and replace the highlighted text with xxxxx
.
The following will do the job in all the major browsers:
function replaceSelectedText(replacementText) {
var sel, range;
if (window.getSelection) {
sel = window.getSelection();
if (sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
range.insertNode(document.createTextNode(replacementText));
}
} else if (document.selection && document.selection.createRange) {
range = document.selection.createRange();
range.text = replacementText;
}
}