Basj
Basj

Reputation: 46333

Get occurence between @ and textarea current position

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

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>

Upvotes: 1

Views: 752

Answers (1)

mplungjan
mplungjan

Reputation: 178383

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>

Upvotes: 5

Related Questions