Highlight all word matches of sentence of text JavaScript


I am trying to highlight all text that match any word of my search text.

Assume search text all text

My query return all record which text contains any of word of above text (Same as text search in MSSQL)

Now i need to highlight all matches with any word in search. My current code can highlight only full text.

My Current Code:

getHighlightedText(text, higlight) {
  let parts = text.split(new RegExp(`(${higlight})`, 'gi'));
  return <span> { parts.map((part, i) => 
    <span key={i} style={part.toLowerCase() === higlight.toLowerCase() ? { color: '#93C74B' } : {} }>{part}</span>)
  } </span>;

Thanks in advance.


You can do this using replace, here is an example:

const getHighlightedText = (text, higlight) => {
  let groups = higlight.split(" ").map(v => `(${v})`).join("|");
  return "<span>" + text.replace(new RegExp(groups, "gi"), g => `<span style="color:#93C74B">${g}</span>`) + "<span>";
let text = "Some text for testing";
let higlight = "TEXT testing";
document.write(getHighlightedText(text, higlight));

What this does is to first generate a regex from the searched string, regex that has this structure (word1)|(word2)...., then replace is used to replace all these words with <span> elements that have a different text color. If you want to learn more about using replace with a function you can do that HERE

Answered By – Titus

Answer Checked By – Mildred Charles (AngularFixing Admin)

Leave a Reply

Your email address will not be published.