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