Replace word before cursor, when multiple lines in

2019-04-09 18:35发布

问题:

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:

  1. totally works for the first paragraph of the contenteditable div
  2. 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.

回答1:

This works:

document.addEventListener("keydown", function(e) {
    var elt = e.target;
    if (elt.isContentEditable)
    {        
        if (e.keyCode == 9) {
            e.preventDefault();
            elt.focus();
            sel = document.getSelection();
            sel.modify("extend", "backward", "word");
            range = sel.getRangeAt(0);
            console.log(range.toString().trim());
            range.deleteContents();
            var el = document.createElement("div");
            el.innerHTML = '<b>test</b> and a <a href="hjkh">link</a>';
            var frag = document.createDocumentFragment(), node;
            while (node = el.firstChild) {
                frag.appendChild(node);
            }
            range.insertNode(frag);
            range.collapse();
        }
    }
});
<div contenteditable>Hello, press TAB to replace this WORD<br>Also press TAB after this ONE</div>

This is a full solution for both textarea and contenteditable div.