Occurrence between current and current position textarea

I would like to get the word after @depending on the current position of the record textarea. More precisely:

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

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

I struggle with this, but I don’t find a “good” 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 me this is a long text, here is another @username cheers!</textarea>
<span id="hey">CLICK ME</span>
Run codeHide result
0
source share
1 answer

Updating the code from the supposed duplicate Get the current word in the 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>
Run codeHide result
+2
source

All Articles