var input = document.getElementById("div_id");
var username = "TEST";
input.focus();
var selection = window.getSelection();
var range = selection.getRangeAt(0);
var span = document.createElement('span');
span.setAttribute('class', 'tagged-user');
span.setAttribute('id', 55);
span.innerHTML = username;
//var initialText = input.textContent;
//var before_caret = initialText.slice(0,getCaretPosition(input));
// var after_caret = initialText.slice(getCaretPosition(input), initialText.length);
// // var before_caret = input.textContent;
// console.log("before_caret " + before_caret);
// *******************************
//this is the regex that match last @something before caret and it work good.
//var droped_at = before_caret.replace(/@\w+(?!.*@\w+)/g, '');
// *******************************
// input.textContent = droped_at + after_caret;
// console.log("before_caret " + before_caret);
range.deleteContents();
range.insertNode(span);
range.collapse(false);
range.insertNode(document.createTextNode("\u00a0"));
// cursor at the last
range.collapse(false);
selection.removeAllRanges();
selection.addRange(range);
.tagged-user {
color: #1e81d6;
font-weight: bold;
}
<div contenteditable="true" id="div_id">
First person <span class="tagged-user" id="1">@Joe </span> and @te and <span class="tagged-user" id="2">@Emilie</span> want to go to the beach.
</div>
An example of a text:
hello man, @te @emilie how are you?
( @emilie is a span tag)
In this example if the cursor is after @te, I want to replace @te by TEST.
Hello,
I am trying to make a facebook like mention system. I'm able to trigger a message that shows a list of all my contacts as soon as I type "@".
Everything is working fine, the only problem is when I type "@te" for finding "TEST" in the list, it should be able to replace "@te" with "TEST". It inputs @teTEST, any clue how to do it ? I'm using a div
with contenteditable
.
Thanks a lot.