Home > Net >  how to highlight specific text in a string displayed in a div?
how to highlight specific text in a string displayed in a div?

Time:10-27

        <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?

CodePudding user response:

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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>
  • Related