Skip to content

Instantly share code, notes, and snippets.

@firestar300
Created December 18, 2019 10:47
Show Gist options
  • Save firestar300/3f77ae105902390a2bd1735d5195ea3d to your computer and use it in GitHub Desktop.
Save firestar300/3f77ae105902390a2bd1735d5195ea3d to your computer and use it in GitHub Desktop.
Highlight text
/**
* Escape Regex if string has any symbols
* @param {String} input input string to escape
*/
const escapeRegExp = input => {
if (/\W|[_]/g.test(input)) {
return input.replace(/\W|_/g, '[$&]')
}
return input
}
/**
* Highlight text
* @param {String} source source string to be highlighted
* @param {String} input input string to escape
*/
export const highlightText = (source, input) => source.replace(new RegExp(escapeRegExp(input), 'gi'), '<em>$&</em>')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment