'How to search multiple keywords in paragraph and highlight the each keyword with different color in javascript using ReactJS?
I want to search one or multiple keywords from multiple bunch of texts, and trying to highlight each keyword with different color. I am using ReactJS redux.
I tried to do the same using Regex but i'm getting the same result what i want. It is working fine when i'm searching only one keyword. But when i'm searching more than one keywords, it display the same keyword multiple times.
And Please help to highlight different keyword with different colors. I am not able to achieve it.
export default class SolrSearchComponent extends Component {
render(){
var allText = "Sea and Sky is your one-stop source for all things related. Sea and Sky is your one-stop source for all things related.";
var KeywordsTosearch = ["Sea", "sky"];
var parts = allText.split(new RegExp(`(${KeywordsTosearch.join("|")})`, "gi"));
var tempKeyword=[];
tempKeyword.push(
<span>
{ parts.map((part, i) =>
KeywordsTosearch.map((keyword,i) =>
<span key={i} style={ part.toLowerCase() === keyword.toLowerCase() ? { fontWeight: 'bold', color: 'red' } : {} }>
{ part }
</span>)
)
}
</span>
);
retrun(
<div>
{tempKeyword}
</div>
)
}
}
I'm expecting multiple keywords highlighted in different colors in result and also text should not print multiple times.
If i'm searching "Sea Sky" it show following in result :
Sea and Sky Sea and Sky is your one-stop source for all things related is your one-stop source for all things related. Sea and Sky Sea and Sky is your one-stop source for all things related is your one-stop source for all things related.
I want result like this:
Sea and Sky is your one-stop source for all things related. Sea and Sky is your one-stop source for all things related.
Note: Sea should be in red text and sky in blue text color.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
