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

289
Visualizações
how to highlight specific text in a string displayed in a div?
        <div
          style={{ color: "white" }}
          dangerouslySetInnerHTML={{
            __html: `text <i style="color: red" >some data </i> not interesting`,
          }}
        />

So this is a way to convert string into html element.

That is not what I am trying to do because it is dangerous.

For example, I want to be able to color every instance of the word "devil" to red in a string displayed in a div.

How can this be done without converting the text into an html element?

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

0

You can use replace method to highlight specific word along with global attribute g to replace all words

function highlight() {
  var textHigh = document.getElementById("text")
  textHigh.innerHTML = textHigh.innerHTML.replace(/ready/g, '<i style="color: red">ready</i>')
}
highlight();
<div id="text">I am everready for every ready state to keep the work ready</div>

about 4 years ago · Juan Pablo Isaza Relatório

0

If you want to stick to React (without directly modifying the DOM), you can iterate over each word/token and replace the word devil with <span className="devil">devil<span> but this gets tricky with punctuation etc. It is a start though. I think @Rana's solution is probably best for what you are looking to do.

  <div style={{ color: "white" }}>{
      textblockyouprovide.split(" ").map(word=>word=="devil"?<span className="devil">word</span>:word)
  }</div>
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