A couple of things before I have an attempt at this:
Please do not add elements into the dom as strings - "return ..". You'll have a hard time performing other actions with this node. Instead I suggest, you use DOM APIs (create/remove/replace/append/etc) to perform these functions. My suggestion will be clear as you read through.
You return a new string and you blindly set the HTML to that particular string - you are losing all the text before it. Example: Hello my name is @testuser1 becomes only @ - you lose "Hello my name is"
Solution:
To take care of carrot placements, you have to remember the selection of the user. Note - if you change the HTML, the browser will lose this selection; hence, you need to track this manually.
Before you 'replace' the text, you can get the selection by:
//IE & Others
if (window.getSelection) {
userSelection = window.getSelection();
} else if (document.selection) {
userSelection = document.selection.createRange();
}
selectedNode = userSelection.anchorNode;
selectedOffset = userSelection.anchorOffset;
After you replace the text, you need to set the selection back to the container.
//IE & Others
var range,
selection;
if (window.getSelection) {
selection = window.getSelection();
range = document.createRange();
range.setStart(targetElement, targetOffset);
range.setEnd(targetElement, targetOffset);
selection.removeAllRanges();
selection.addRange(range);
} else if (document.selection) {
range = document.selection.createRange();
range.moveToElementText(targetElement.parentElement);
range.collapse(true);
range.moveEnd('character', targetOffset);
range.moveStart('character', targetOffset);
range.select();
}
}
The target Element and the target offset is the node you want to target and the postion (from the left) you want the cursor to be.
Now that the basics are over, here comes the hard part:
When you break up the text (TextNode) by putting in an anchor element, you need to have the target element as the anchor element and the offset to be the length of the text inside the anchor element. This would be much easier if you use DOM APIs and store this element as a variable.
You need to cater to situations where the user might go to any part of the text and enter @username1; this should be fairly simple.
You could also play around with Rangy JS lib to achieve this.
Have fun!