Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to replace matching words within a page replacing the body.innerHTML only once?

The following function in JavaScript adds to each matching word a <mark> tag in the document’s body.

var words = ["apple", "banana", "carrot", "pear"];  

for (var i=0; i < words.length; i++) {
  var replace = new RegExp(words[i],"g");
  var page = document.body.innerHTML;
  var newPage = page.replace(replace, `<mark>${words[i]}</mark>`);
  document.body.innerHTML = newPage;
}

This way, it highlights a word within the <body> if it’s an element within the array words.

The issue I have is that the document.body.innerHTML is replaced at every iteration. Do you know how I can replace the matching words in the page limiting the numbers of document.body.innerHTML = newPage to 1?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks in advance for your replies!

>Solution :

Get innerHTML before loop and set innerHTML after loo. you can use replaceAll to change all matching word

var words = ["apple", "banana", "carrot", "pear"];
var page = document.body.innerHTML;

words.forEach((word)  => {
  page = page.replaceAll(word, `<mark>${word}</mark>`);
});

document.body.innerHTML = page;
<div> apple abc banana cd apple </div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading