在textarea中找到插入符号之前的部分单词 [英] Find part of word before caret in textarea

查看:63
本文介绍了在textarea中找到插入符号之前的部分单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个jQuery插件,可以找到textarea的插入位置。我在textarea的keyup函数上实现它,如下所示:

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?

推荐答案

如果你为此,我正在使用我的jQuery textarea插件,选择字符位置始终相对于无论浏览器如何处理换行符,textarea的属性。然后你可以得到如下的最后一句话:

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:

注意你必须使用textarea的属性而不是jQuery的 val()方法,用于规范换行符。

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

这篇关于在textarea中找到插入符号之前的部分单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆