Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

205
Visualizações
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?

Thanks in advance for your replies!

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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>

about 4 years ago · Juan Pablo Isaza Relatório

0

Read the string before the loop, modify it in the loop, and change the document body after the loop.

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

for (const word of words) {
  page = page.replaceAll(word, `<mark>${word}</mark>`);
}
document.body.innerHTML = page;
"apple", "banana", "carrot", "pear"

Or you can use reduce:

const words = ["apple", "banana", "carrot", "pear"];  
document.body.innerHTML = words.reduce((page, word) => page.replaceAll(word, `<mark>${word}</mark>`), document.body.innerHTML);
"apple", "banana", "carrot", "pear"

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda