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!