Div “contenteditable” : get and delete word preced

2020-03-24 11:20发布

问题:

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

Here's a fiddle, and here's the function:

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;
    }
}

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.

Thank you in advance!

回答1:

You could try using index property of match()

var lastWordPosition = preceding.match(/(?:\s|^)([\S]+)$/i).index;

Then you can do a substring(0, lastWordPosition) or whatever you want…



回答2:

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(/\b/g) //if you want the last word until a non caractere
        .pop()
        .trim()
    );
  }
  return "";
}