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 badges1 Answer
Reset to default 8If 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
评论列表(0条)