用Javascript中的新HTML字符串替换字符串中的所有单词

时间:2022-09-13 12:20:12

I am trying to replace a string like:

我想替换一个字符串,如:

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

by a new string contains HTML like:

通过一个新的字符串包含HTML,如:

<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:

通过这种方式,它将返回HTML,如:

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

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

我只想替换整个单词“@xxx”。我怎样才能做到这一点?

2 个解决方案

#1


1  

alert("@xxx test@xxx.com @xxx @xxx".replace(/(\B@xxx)/g, "<a href>$1</a>"));

#2


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

样品

#1


1  

alert("@xxx test@xxx.com @xxx @xxx".replace(/(\B@xxx)/g, "<a href>$1</a>"));

#2


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

样品