Get the word upon which the caret sits within a contenteditable div?
You could use the new TextRange module of my Rangy library for this, although it's enormous overkill just for that one feature. Here's the code you'd need:
var sel = rangy.getSelection();
sel.expand("word");
var word = sel.text();
alert(word);
Otherwise, if you can live with no support for pre-Blink Opera (up to and including version 12) and Firefox < 4, you could use Selection.modify()
(WebKit, Firefox) and the expand()
method of TextRange
(IE). Here's an example.
Demo: http://jsfiddle.net/timdown/dBgHn/1/
Code:
function getWord() {
var sel, word = "";
if (window.getSelection && (sel = window.getSelection()).modify) {
var selectedRange = sel.getRangeAt(0);
sel.collapseToStart();
sel.modify("move", "backward", "word");
sel.modify("extend", "forward", "word");
word = sel.toString();
// Restore selection
sel.removeAllRanges();
sel.addRange(selectedRange);
} else if ( (sel = document.selection) && sel.type != "Control") {
var range = sel.createRange();
range.collapse(true);
range.expand("word");
word = range.text;
}
alert(word);
}