Div “contenteditable” : get and delete word preceding caret

后端 未结 2 1394
感动是毒
感动是毒 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 "";
    }
    
    

提交回复
热议问题