Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

288
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!