0

I would like to highlight some keywords within a string. Then display it in html.

Here is my code in react

var samplestring = "You've gotta dance like there's nobody watching, Love like you'll never be hurt, Sing like there's nobody listening, And live like it's heaven on earth.";

const samplearray = ["dance","Love","Sing"]

function Highlight() {
  const highlighter = () => {
  
    samplearray.forEach(str => {
      samplestring = samplestring.replaceAll(str, `<span class='asd'>${str}</span>`)
    })

    return samplestring

  }

  return <div className="App">{highlighter()}</div>
}

export default Highlight

Result:

This what I see in browser enter image description here

You've gotta <span class='asd'>dance</span> like there's nobody watching, <span class='asd'>Love</span> like you'll never be hurt, <span class='asd'>Sing</span> like there's nobody listening, And live like it's heaven on earth.

However, my expectation is to make span as html tag, instead of part of a string.

May I know how to do it?

  • Return an array of components from `highlighter` instead of a string, since a string will be like setting the `.textContent` - unformatted – CertainPerformance Jun 30 '22 at 04:05
  • can you show me some code to explain what you mean? –  Jun 30 '22 at 04:09
  • See the canonical - it has a number of answers on it – CertainPerformance Jun 30 '22 at 04:09
  • I mean, according to my code, what is the adjusted code you suggest. Yea, ofc, there may be number of similar questions outside, but how to change it according to the code? it would be more helpful than just pointing some other posts. –  Jun 30 '22 at 04:14

0 Answers0