How can i surround certain letters in a string by an html tag?
For example, given this string: Sgt. Pepper's Lonely Hearts Club Band and this substring: Pepp. I want to surround the substring inside the string with an html tag. Like this: Sgt. <mark class="Search-suggestions-match">Pepp</mark>er's Lonely Hearts Club Band.
I achieved this, but React is escaping the span tags. But also, i don't know if i should take another approach, maybe a more JSX one.
This is the component where im trying to implement it:
class SearchSuggestions extends Component {
constructor(props) {
super(props)
if (!this.props.suggestions || !this.props.term) {
return
}
this.state = {
suggestions : this.props.suggestions.map(item => this.markText(item))
}
}
markText(string) {
return string.replace(new RegExp(this.props.term, "ig"), match => {
return `<mark class="Search-suggestions-match">${match}</mark>`
})
}
render() {
if (!this.props.suggestions || !this.props.term) {
return null
}
return (
<ul className="Search-suggestions-component">
{this.state.suggestions.map((value, i) => <li key={i}>{value}</li>)}
</ul>
)
}
}