javascript - Find part of word before caret in textarea - Stack Overflow

I have a jQuery plugin that finds the caret position of a textarea. I implement it on the keyup functio

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?

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?

Share Improve this question asked Apr 8, 2011 at 5:10 Peter OlsonPeter Olson 143k49 gold badges208 silver badges249 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

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);
});

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745328224a4622756.html

相关推荐

  • javascript - Find part of word before caret in textarea - Stack Overflow

    I have a jQuery plugin that finds the caret position of a textarea. I implement it on the keyup functio

    7小时前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信