div“内容可编辑": 获取和删除插入符号前的单词

感谢这个问题和蒂姆发布的答案下来,我做了一个函数来获取contenteditable"div中插入符号前面的单词.

Thanks to this question and answer posted by Tim Down, I made a function to get the word preceding caret in a "contenteditable" div.

这是一个fiddle,函数如下:

function getWordPrecedingCaret (containerEl) {
    var preceding = "",
        sel,
        range,
        precedingRange;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.rangeCount > 0) {
            range = sel.getRangeAt(0).cloneRange();
            range.collapse(true);
            range.setStart(containerEl, 0);
            preceding = range.toString();
        }
    } else if ((sel = document.selection) && sel.type != "Control") {
        range = sel.createRange();
        precedingRange = range.duplicate();
        precedingRange.moveToElementText(containerEl);
        precedingRange.setEndPoint("EndToStart", range);
        preceding = precedingRange.text;
    }
    var lastWord = preceding.match(/(?:s|^)([S]+)$/i);
    if (lastWord) {
        return lastWord;
    } else {
        return false;
    }
}

我的问题:一旦得到最后一个字,我怎样才能将它从 div 中删除?请注意,我不想删除 div 中出现的任何单词,只删除插入符号之前的单词.

My question: Once gotten the last word, how can I remove it from the div? Note that I don't want to remove any occurrence of the word in the div, only occurrence preceding the caret.

提前谢谢你!

推荐答案

一个很好的解决方案,在插入符号之前获得单词

A nice solution to get the word before the caret

export function getWordBeforeCare() {
  const range = window.getSelection().getRangeAt(0);
  if (range.collapsed) {
    const text = range.startContainer.textContent.substring(
      0,
      range.startOffset + 1
    );
    return (
      text
        .split(/s/g) // if you want the last word until the space
        // .split(//g) //if you want the last word until a non caractere
        .pop()
        .trim()
    );
  }
  return "";
}

相关文章