Search code examples
jquerystringtextareacpu-wordgetcaretpos

Get current word on caret position


How can I get a word in textarrea by its current caret position?

I tried something like this, however this returns just the words first letter upto the character at caret position. For example:

if the cursor is between fo and o it returns fo and not foo as excpected.

Fo|o bar is not equal to bar foo. => Fo expects Foo

Foo bar is not equ|al to bar foo. => equ expects equal.

Here's what I've done so far:

function getCaretPosition(ctrl) {
    var start, end;
    if (ctrl.setSelectionRange) {
        start = ctrl.selectionStart;
        end = ctrl.selectionEnd;
    } else if (document.selection && document.selection.createRange) {
        var range = document.selection.createRange();
        start = 0 - range.duplicate().moveStart('character', -100000);
        end = start + range.text.length;
    }
    return {
        start: start,
        end: end
    }
}

$("textarea").keyup(function () {
    var caret = getCaretPosition(this);

    var result = /\S+$/.exec(this.value.slice(0, caret.end));
    var lastWord = result ? result[0] : null;
    alert(lastWord);
});

http://fiddle.jshell.net/gANLv/


Solution

  • Try change this line in your code to this:

     var result = /\S+$/.exec(this.value.slice(0, this.value.indexOf(' ',caret.end)));