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: if the current cursor position is on any letter of @, the ans
Solution 1:
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>
Post a Comment for "Get Occurence Between @ And Textarea Current Position"