Reputation: 15
I want to replace all the occurrences of a particular word in the web page using javascript.
Sample Sentence = "Hi Guys, I have a lot of things. The things are good. They are beautiful-things. Look at /home/things.html"
I am using
document.body.innerHTML =
document.body.innerHTML.replace(/\bthings\b/g, function (x) {
return 'OBJECTS';
});
But this replaced like this
Hi Guys, I have a lot of OBJECTS. The OBJECTS are good. They are beautiful-OBJECTS. Look at /home/OBJECTS.html
I want to replace only whole words. Not (beautiful-things), (/home/things.html) should not be replaced. I want to replace only (things).
Upvotes: 1
Views: 485
Reputation: 1994
Ritesh answer will work fine most of the time, but it won't when the word you want to replace is the first one in the text (unless you put an extra white space before it, which you probably don't want to).
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
Upvotes: 0
Reputation: 4005
Try this:
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
Upvotes: 1