I have an autocomplete user-tagging system that fills in usernames that come after an @ symbol. I have this problem however, where I have two users with a matching substring. For example:
Tagging @billy and @b
When a user fills in the @b tag with a user named (for example) @brendan, it'll replace the @billy tag. How do I go backwards and replace only the last tag?
Edit: this is my current solution, but it feels kludgy. Is there a way to do this just with RegEx?:
function tagUser (chosenUsername) {
var userRegex = new RegExp('(^|\\s)@([' + lastUserTag() + ']*)$', 'gi');
var caption = $("#example").val();
var match = caption.match(userRegex);
var lastMatch = match[match.length - 1];
$("#example").val(caption.replace(lastMatch, " @" + chosenUsername));
}
Not sure if I understood your problem entirely. However just to let you know you can use negative lookahead to replace only last matched text like this:
var str='@billy and @b';
str = str.replace(/@b\b(?!.*?@b\b)/, 'brendan');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.