1

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));
}
1
  • 1
    Can you show us the code that does the replacement? Commented Mar 27, 2013 at 20:35

1 Answer 1

3

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');
Sign up to request clarification or add additional context in comments.

2 Comments

This worked great, but then you edited the '\b'. Can you explain what those are for?
I added \b for word boundary just to avoid matching something like @samuals when you're actually matching @sam.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.