how to highlight specific text in a string displayed in a div?

Issue

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

Solution

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>

Answered By – Rana

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published