Detect the last written word when typing TAB in a textarea or contenteditable div

我只是一个虾纸丫 提交于 2019-11-29 18:37:48

You can use current cursor position to detect last word. A simple example is given bellow.

document.getElementById('foobar').addEventListener('keydown', e => {
  if( e.which == 9 ) {
    e.preventDefault();
    let endingIndex = e.target.selectionStart;
    let startingIndex = endingIndex && endingIndex - 1;
    let value = e.target.value;
    // putt all delemeters in it by which word can be splitted
    let regex = /[ ]/;

    while(startingIndex > -1){
      if(regex.test(value[startingIndex])){
        ++startingIndex;
        break;
      }
      --startingIndex;
    }

    // note you will have you apply check to avoid negative index
    if(startingIndex < 0) {
        startingIndex = 0;
    }
    console.log(value.substring(startingIndex, endingIndex));

    let newText = "replaced";
    value = value.substring(0, startingIndex) + newText + value.substring(endingIndex);
    let cursorPosition = startingIndex + newText.length;
    e.target.value = value;
    e.target.setSelectionRange(cursorPosition, cursorPosition);
  }
  
});
<textarea id="foobar"></textarea>

This totally works for textarea and for contenteditable div:

var newText = 'hello\nnewline';
var newHtml = '<b>test</b> and<br>a <a href="hjkh">link</a>';

document.addEventListener("keydown", function(e) {
    var elt = e.target;
    if (elt.tagName.toLowerCase() === 'textarea' || elt.isContentEditable)
    {        
        if (e.keyCode == 9) {
            e.preventDefault();
            if (elt.isContentEditable) {  // for contenteditable
                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 = newHtml;
                var frag = document.createDocumentFragment(), node;
                while (node = el.firstChild) {
                    frag.appendChild(node);
                }
                range.insertNode(frag);
                range.collapse();
            } else {  // for texterea/input element
                var endingIndex = elt.selectionStart;
                var startingIndex = endingIndex && endingIndex - 1;
                var value = elt.value;
                var regex = /[ ]/;
                while (startingIndex > -1) {
                    if (regex.test(value[startingIndex])) {
                        ++startingIndex;
                        break;
                    }
                    --startingIndex;
                }
                if (startingIndex < 0) {
                    startingIndex = 0;
                }
                value = value.substring(0, startingIndex) + newText + value.substring(endingIndex);
                var cursorPosition = startingIndex + newText.length;
                e.target.value = value;
                e.target.setSelectionRange(cursorPosition, cursorPosition);
            }
        }
    }
});
<div contenteditable>Hello, press TAB to replace this WORD<br>Also press TAB after this ONE</div>
<textarea rows="8" cols="50" id="a">Hello, press TAB to replace this WORD
Also press TAB after this ONE</textarea>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!