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

105
Visualizações
Add new tag to the middle of element

I am trying to surround specific words in textContent with HTML tags, this could hypothetically be done by doing element.textContent = element.textContent.replaceAll("word", "<h1>word<h1>"); but that isn't parsed, and element.innerHTML= element.innerHTML.replaceAll("word", "<h1>word<h1>"); doesn't work because there is a risk that the word could be the name of a tag. Is there any solution besides writing a custom replace function that detects when in a tag?

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

0

You can make sure that the word you're trying to pad is not inside a tag. To do this, you need to check its surrounding characters. As long as they aren't enclosed by < and > on both sides (or make sure they are enclosed by <some tag> on the left and </?some tag> on the right like what I did below), they should be the only one to be replaced. Try this regex sample below:

function padTags(content, openTag, word, closeTag) {
  console.log(content)
  const replacement = openTag + word + closeTag;
  const regex = `(?<!<[^<>]*)${word}(?![^<>]*>)`;
  const pattern = new RegExp(regex, 'g');
  return content.replace(pattern, replacement);
}

console.log(padTags(`<p class="questions">What's your favorite class?</p>`, 
                '<custom-tag>', 'class', '</custom-tag>'));
console.log(padTags(`<div><p class="test">class</p></div>`,
                '<custom-tag>', 'class', '</custom-tag>'));
console.log(padTags(`<div> class <p data-customvar="<class>">This is my class </p>class</div>`,
                '<custom-tag>', 'class', '</custom-tag>'));

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