开发者

Find part of word before caret in textarea

开发者 https://www.devze.com 2023-02-23 03:09 出处:网络
I have a jQuery plugin that finds the caret position of a textarea. I implement it on the keyup function of the textarea, like this:

I have a jQuery plugin that finds the caret position of a textarea. I implement it on the keyup function of the textarea, like this:

$("#editor").keyup(function () {
   var textbox = $(this);
   var end = textbox.getSelection().end;
});

I am wanting to find the word, or part of a word, before the caret. Words are delimited by any type of whitespace.

My main difficulty in doing this is dealing with line breaks. How can I find the word or part of a word immediately before the caret given the character开发者_如何转开发 index of the caret?


If you're using my jQuery textarea plug-in for this, the selection character positions are always relative to the value property of the textarea, regardless of how the browser handles line breaks. You could then get the last word as follows:

Note that you have to use the textarea's value property and not jQuery's val() method, which normalizes line breaks.

$("#editor").keyup(function () {
    var textbox = $(this);
    var end = textbox.getSelection().end;
    var result = /\S+$/.exec(this.value.slice(0, end));
    var lastWord = result ? result[0] : null;
    alert(lastWord);
});
0

精彩评论

暂无评论...
验证码 换一张
取 消