Last active
March 23, 2024 18:37
-
-
Save wojtekmaj/f265f55e89ccb4ce70fbd2f8c7b1d95d to your computer and use it in GitHub Desktop.
Highlight text in React by providing text and RegExp pattern.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]), []); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Easy to do so here : https://www.npmjs.com/package/reactjs-editor?activeTab=readme
Demo here: https://reactjs-editor-demo.vercel.app/