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