首页 > 解决方案 > 使用 JavaScript 仅查找和替换 HTML 中的整个单词?

问题描述

我想使用 javascript 替换网页中所有出现的特定单词。

示例句子 ="Hi Guys, I have a lot of things. The things are good. They are beautiful-things. Look at /home/things.html"

我在用

document.body.innerHTML = 
document.body.innerHTML.replace(/\bthings\b/g, function (x) {
return 'OBJECTS';
});

但是这样替换了

Hi Guys, I have a lot of OBJECTS. The OBJECTS are good. They are beautiful-OBJECTS. Look at /home/OBJECTS.html

我只想替换整个单词。Not (beautiful-things), (/home/things.html) 不应该被替换。我只想更换(东西)。

标签: javascriptregex

解决方案


试试这个:

document.body.innerHTML = 
document.body.innerHTML.replace(/\sthings\b/g,' OBJECTS');
Hi Guys, I have a lot of things. The things are good. They are beautiful-things. Look at /home/things.html


推荐阅读