Skip to content

Instantly share code, notes, and snippets.

@dlong500
Created February 14, 2024 00:54
Show Gist options
  • Save dlong500/51a7aeb716b9496bb0e9b62750154282 to your computer and use it in GitHub Desktop.
Save dlong500/51a7aeb716b9496bb0e9b62750154282 to your computer and use it in GitHub Desktop.
regex text/JSX highlighters
// 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