I want to replace the word before cursor in contenteditable
div (see also Detect the last written word when typing TAB in a textarea or contenteditable div).
The following code:
- totally works for the first paragraph of the
contenteditable
div does not work for the next paragraphs of the
contenteditable
div:Uncaught IndexSizeError: Failed to execute 'setStart' on 'Range': The offset 71 is larger than the node's length (38).
How should I modify the following code to make it work when pressing TAB in the 2nd line of the contenteditable
div?
document.addEventListener("keydown", function(e) {
var elt = e.target;
if (elt.isContentEditable)
{
if (e.keyCode == 9) {
e.preventDefault();
elt.focus();
range = document.getSelection().getRangeAt(0).cloneRange();
range.collapse(true);
range.setStart(elt, 0);
var words = range.toString().trim().split(' ');
var lastWord = words[words.length - 1];
if (lastWord) {
var wordStart = range.toString().lastIndexOf(lastWord);
var wordEnd = wordStart + lastWord.length;
range.setStart(elt.firstChild, wordStart);
range.setEnd(elt.firstChild, wordEnd);
range.deleteContents();
document.execCommand('insertText', false, "hello\nnewline");
elt.normalize();
}
}
}
});
<div contenteditable>Hello, click here and press TAB to replace this WORD<br>Also click here and press TAB after this ONE</div>
Note: I've already tested the answer from Replace specific word in contenteditable but it doesn't work when there are multiple lines in the contenteditable div.