Pahalavan
Pahalavan

Reputation: 15

Find and Replace only Whole word in HTML using JavaScript?

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

Answers (2)

alotropico
alotropico

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

Ritesh Khandekar
Ritesh Khandekar

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

Related Questions