Skip to content

Instantly share code, notes, and snippets.

@DRFR0ST
Last active September 6, 2019 16:07
Show Gist options
  • Save DRFR0ST/d7439d102bd741043aebb9c40eefb000 to your computer and use it in GitHub Desktop.
Save DRFR0ST/d7439d102bd741043aebb9c40eefb000 to your computer and use it in GitHub Desktop.
Returns highlighted text (component) by passing it the text and an array of strings which will be highlighted. (React)
function getHighlightedText(text, highlights) {
let parts = text.split(new RegExp(`(${highlights.join("|")})`, "gi"));
return (
<span>
{parts.map((part, i) => (
<span
key={i}
style={highlights.indexOf(part) > -1 ? { fontWeight: "bold" } : {}}>
{part}
</span>
))}
</span>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment