我正在尝试替换如下字符串:
var str = "@xxx <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7f0b1a0c0b3f070707511c1012" rel="noreferrer noopener nofollow">[email protected]</a>"
由一个包含 HTML 的新字符串组成,例如:
<a href>@xxx</a> <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="097d6c7a7d49717171276a6664" rel="noreferrer noopener nofollow">[email protected]</a>
我尝试用这种方式替换但不正确:
str = str.replace(/@xxx/g, "<a href>@xxx</a>")
通过这种方式,它将返回如下 HTML:
<a href>@xxx</a> test<a href>@xxx</a>.com
我只想替换整个单词“@xxx”。我怎样才能做到这一点?
最佳答案
alert("@xxx <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0470617770447c7c7c2a676b69" rel="noreferrer noopener nofollow">[email protected]</a> @xxx @xxx".replace(/(\B@xxx)/g, "<a href>$1</a>"));
关于javascript - 在 Javascript 中用新的 HTML 字符串替换字符串中的所有单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32165533/