The following function in JavaScript
adds to each matching word a <mark>
tag in the document’s body.
JavaScript
x
9
1
var words = ["apple", "banana", "carrot", "pear"];
2
3
for (var i=0; i < words.length; i++) {
4
var replace = new RegExp(words[i],"g");
5
var page = document.body.innerHTML;
6
var newPage = page.replace(replace, `<mark>${words[i]}</mark>`);
7
document.body.innerHTML = newPage;
8
}
9
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?
Thanks in advance for your replies!
Advertisement
Answer
Get innerHTML before loop and set innerHTML after loo. you can use replaceAll to change all matching word
JavaScript
1
8
1
var words = ["apple", "banana", "carrot", "pear"];
2
var page = document.body.innerHTML;
3
4
words.forEach((word) => {
5
page = page.replaceAll(word, `<mark>${word}</mark>`);
6
});
7
8
document.body.innerHTML = page;
JavaScript
1
1
1
<div> apple abc banana cd apple </div>