2

I am trying to replace a string like:

var str = "@xxx [email protected]"

by a new string contains HTML like:

<a href>@xxx</a> [email protected]

I tried to this way to replace but not correct:

str = str.replace(/@xxx/g, "<a href>@xxx</a>")

With this way, it will return HTML like:

<a href>@xxx</a> test<a href>@xxx</a>.com

I just want to replace whole word "@xxx". How can I do that?

4
  • possible duplicate of Why does javascript replace only first instance when using replace? Commented Aug 23, 2015 at 10:17
  • well, my question is different Commented Aug 23, 2015 at 10:18
  • The other question includes the answer to this question: simply remove the g flag to not do a global replace. Commented Aug 23, 2015 at 10:22
  • I really need to do a global replace all the word "@xxx" Commented Aug 23, 2015 at 10:26

2 Answers 2

1

alert("@xxx [email protected] @xxx @xxx".replace(/(\B@xxx)/g, "<a href>$1</a>"));

Sign up to request clarification or add additional context in comments.

Comments

1

Let's just keep it nice and clean....

var string = '@xxx [email protected]',
regger = /(@\S+)\s(.+.com)/,
output = string.replace(regger,"<a href='$1'>$2</a>")

Sample

1 Comment

Downvoting people providing you with answers, let alone correct answers, isn't very nice.

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.