我需要使用javascript和regex替换文本。这样单词borex,edge和rss feed将替换为 borex , edge 和 rss feed 。 文字看起来像这样。
<body>
<img src="http://some.web.site/image.jpg" title="borex" />
These words are highlighted: borex, edge, rss feeds while these words are not: bewedge, borexlumina, rss feedssss
</body>
替换为:
<body>
<img src="http://some.web.site/image.jpg" title="borex" />
These words are highlighted: <b>borex</b>, <b>edge</b>, <b>rss feeds</b> while these words are not: bewedge, borexlumina, rss feedssss
</body>
我试过了:
var str = document.getElementByTagName("body")
str.replace(/borex/g,'<b>borex</b>').replace(/edge/g,'<b>edge</b>').replace(/rss feeds/,'<b>rss feeds</b>')
这将获得所有这些。我如何只获得不属于另一个词的单词?欢迎任何其他建议..需要一些帮助...
答案 0 :(得分:5)
使用\b
表示a word boundry:
str.replace(/\b(borex|edge|rss feeds)\b/g, '<b>$1</b>');
答案 1 :(得分:3)
使用正则表达式word boundaries:
str.replace(/\bborex\b/g,'<b>borex</b>').replace(/\bedge\b/g,'<b>edge</b>').replace(/\brss feeds\b/,'<b>rss feeds</b>')