Div “contenteditable” : get and delete word preceding caret

后端 未结 2 1391
感动是毒
感动是毒 2021-01-14 00:22

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

相关标签:
2条回答
  • 2021-01-14 00:52

    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 "";
    }
    
    
    0 讨论(0)
  • 2021-01-14 01:17

    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…

    0 讨论(0)
提交回复
热议问题