0

I have some simple regex that should replace @Username to

<a href="http://google.com">@Username</a>

Though its getting very odd results.

REGEX

var msg="@Mr.EasyBB";
msg.replace(/@(.+?)/g,
'<a href=\"http://'+window.location.host+'/u=$1\">$1</a>');

can someone help with this small issue results look like this

<a href="http://google.com">@U</a>sername
5
  • 1
    "Though its getting very odd results." For example? Commented Mar 9, 2014 at 18:52
  • Seems fine here fiddle Commented Mar 9, 2014 at 18:52
  • You edited the result lol. It's only getting @U and not @Username as a whole. I think I need to look ahead till white space. but not sure how Commented Mar 9, 2014 at 18:53
  • The ? should be outside the (). /@(.+)?/g Commented Mar 9, 2014 at 18:54
  • Remove ? is not greedy. (.+) will just do it. Commented Mar 9, 2014 at 18:55

2 Answers 2

1

.+? is lazy matching - this will match as few characters as it can.

Try this. It will match as many non-whitespace characters as it can.

/@(\S+)/
Sign up to request clarification or add additional context in comments.

2 Comments

Originally /@(\S+\b)/. Sabuj Hassan got the final version first, although both should work.
Thanks guys. I now understand lazy operators better :D I thought lazy was keep going don't stop until success which I get that now success would be the one character...those lazy sons of a guns :D
1

Try this one:

msg = msg.replace(/@(\S+)/g, '<a href=\"http://'+window.location.host+'/u=$1\">@$1</a>');

Comments

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.