How can I get a word in textarrea by its current caret position?
I tried something like this, but this only returns the first letter words to the character in the carriage position. For instance:
if the cursor is between fo and o, it returns fo, and not fooas intended.
Fo |o bar is not equal to bar foo. => fopendingfoo
Foo bar is not equ |al for bar foo. => equpending equal.
Here is what I have 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/
source
share