JavaScript get word before cursor

Lennart picture Lennart · Mar 31, 2012 · Viewed 10.2k times · Source

Okay, I've been looking all over the web to find a solution but I couldn't find one, is there a way to get the word before the caret position in an editable div so a bit like:

This is some| demo texts

This should return the word "some"... I don't know if this is possible, I would be glad for any help, thanks :).

Answer

Özgür Kaplan picture Özgür Kaplan · Mar 31, 2012

With using Caret Position finder method provided here this will do what you want.

function ReturnWord(text, caretPos) {
    var index = text.indexOf(caretPos);
    var preText = text.substring(0, caretPos);
    if (preText.indexOf(" ") > 0) {
        var words = preText.split(" ");
        return words[words.length - 1]; //return last word
    }
    else {
        return preText;
    }
}

function AlertPrevWord() {
    var text = document.getElementById("textArea");
    var caretPos = GetCaretPosition(text)
    var word = ReturnWord(text.value, caretPos);
    if (word != null) {
        alert(word);
    }

}

function GetCaretPosition(ctrl) {
    var CaretPos = 0;   // IE Support
    if (document.selection) {
        ctrl.focus();
        var Sel = document.selection.createRange();
        Sel.moveStart('character', -ctrl.value.length);
        CaretPos = Sel.text.length;
    }
    // Firefox support
    else if (ctrl.selectionStart || ctrl.selectionStart == '0')
        CaretPos = ctrl.selectionStart;
    return (CaretPos);
}
<input id="textArea" type="text" />
<br />
<input id="Submit" type="submit" value="Test" onclick="AlertPrevWord()" />

Here is also a jsfiddle.