2

I am trying to replace a string like:

var str = "@xxx test@xxx.com"

by a new string contains HTML like:

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

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?

Snow Fox
  • 389
  • 6
  • 15
  • possible duplicate of [Why does javascript replace only first instance when using replace?](http://stackoverflow.com/questions/1967119/why-does-javascript-replace-only-first-instance-when-using-replace) – Sigroad Aug 23 '15 at 10:17
  • well, my question is different – Snow Fox Aug 23 '15 at 10:18
  • The other question includes the answer to this question: simply remove the g flag to not do a global replace. – Sigroad Aug 23 '15 at 10:22
  • I really need to do a global replace all the word "@xxx" – Snow Fox Aug 23 '15 at 10:26

2 Answers2

1

alert("@xxx test@xxx.com @xxx @xxx".replace(/(\B@xxx)/g, "<a href>$1</a>"));
Vidul
  • 10,128
  • 2
  • 18
  • 20
1

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

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

Sample

Casey Dwayne
  • 2,142
  • 1
  • 17
  • 32