Skip to content

Instantly share code, notes, and snippets.

@wojtekmaj
Last active March 23, 2024 18:37
Show Gist options
  • Save wojtekmaj/f265f55e89ccb4ce70fbd2f8c7b1d95d to your computer and use it in GitHub Desktop.
Save wojtekmaj/f265f55e89ccb4ce70fbd2f8c7b1d95d to your computer and use it in GitHub Desktop.
Highlight text in React by providing text and RegExp pattern.
function highlightPattern(text, pattern) {
const splitText = text.split(pattern);
if (splitText.length <= 1) {
return text;
}
const matches = text.match(pattern);
return splitText.reduce((arr, element, index) => (matches[index] ? [
...arr,
element,
<mark key={index}>
{matches[index]}
</mark>,
] : [...arr, element]), []);
}
@vivekneupane11
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment