繁体   English   中英

使用 JavaScript 仅查找和替换 HTML 中的整个单词?

[英]Find and Replace only Whole word in HTML using JavaScript?

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

Sample Sentence = "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) 不应该被替换。 我只想更换(东西)。

尝试这个:

 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

Ritesh 答案在大多数情况下都可以正常工作,但是当您要替换的单词是文本中的第一个单词时(除非您在它之前放置一个额外的空格,您可能不想这样做),它不会。

 document.body.innerHTML = document.body.innerHTML.replace(/(^|\s)things\b/gi, m => m.replace(/things/i, 'OBJECTS'));
 Things. Hi Guys, I have a lot of things. The things are good. They are beautiful-things. Look at /home/things.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM