Created
February 14, 2024 00:54
-
-
Save dlong500/51a7aeb716b9496bb0e9b62750154282 to your computer and use it in GitHub Desktop.
regex text/JSX highlighters
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
// quick and dirty | |
highlightJSX(stringToEvaluate, searchTerm) { | |
const regex = new RegExp(searchTerm, 'gi'); | |
const resultText = stringToEvaluate.replace(regex, `<mark class="highlight">$&</mark>`); | |
return <span dangerouslySetInnerHTML={{ __html: resultText }} />; | |
} | |
// highlightJSX('this is a string to search and to evaluate', 'to') | |
// expected output | |
// <>this is a string <mark class="highlight">to</mark> search and <mark class="highlight">to</mark> evaluate<> | |
// safer, but slightly more complex | |
import reactStringReplace from 'react-string-replace' | |
const stringToEvaluate = 'this is a string to search and to evaluate' | |
const searchTerm = 'to' | |
const highlightedMatch = reactStringReplace(stringToEvaluate, new RegExp(`(${searchTerm})`, "gi"), (match, i) => ( | |
<span key={i} className='text-boldest' style={{ color: '#F1C40F' }}>{match}</span> | |
)) | |
// expected output | |
// <>this is a string <span key={0} className='text-boldest' style={{ color: '#F1C40F' }}>to</span> search and <span key={1} className='text-boldest' style={{ color: '#F1C40F' }}>to</span> evaluate<> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment