获取@和textarea当前位置之间的出现 [英] Get occurence between @ and textarea current position

查看:72
本文介绍了获取@和textarea当前位置之间的出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在@之后得到单词,具体取决于textarea的当前书写位置.更精确地:

I'd like to get the word after @ depending on the current writing position of a textarea. More precisely:

  • 如果当前光标位置在@<user>的任何字母上,则答案应为<user>

  • if the current cursor position is on any letter of @<user>, the answer should be <user>

如果当前光标位置在任何其他单词上,则答案应为空''

if the current cursor position is on any other word, the answer should be empty ''

我正在为此而苦苦挣扎,但是没有找到任何不错"的方法来实现它.

I'm struggling with this, but don't find any "nice" way to do it.

$('#hey').on('click', function() { alert(); });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

<textarea id="chat">hello @user it's me this is a long text, here is another @username cheers!</textarea>
<span id="hey">CLICK ME</span>

推荐答案

已从假定重复的

Having updated the code from the assumed duplicate Get current word on caret position, the result is as follows

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").on("click keyup", function () {
    var caret = getCaretPosition(this);
    var endPos = this.value.indexOf(' ',caret.end);
    if (endPos ==-1) endPos = this.value.length;
    var result = /\S+$/.exec(this.value.slice(0, endPos));
    var lastWord = result ? result[0] : null;
    if (lastWord) lastWord = lastWord.replace(/['";:,.\/?\\-]$/, ''); // remove punctuation
    $("#atID").html((lastWord && lastWord.indexOf("@") == 0)?lastWord:"");
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<textarea>Follow me on twitter @mplungjan if you want</textarea><br/>
<span id="atID"></span>

这篇关于获取@和textarea当前位置之间的出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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