1

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).

2
  • 1
    You better hope things doesn't appear in the HTML parts (eg. class names)... Commented Jul 19, 2020 at 7:31
  • You can use a Treewalker to traverse all textNodes and find the text to change, depending if your target node has children or not. if not, you can simply use innerHTML Commented Jul 19, 2020 at 7:34

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.