Skip to content

Instantly share code, notes, and snippets.

@frentsel
Created April 17, 2019 10:20
Show Gist options
  • Save frentsel/91419bfe1587ae6cc868d883e0b44c73 to your computer and use it in GitHub Desktop.
Save frentsel/91419bfe1587ae6cc868d883e0b44c73 to your computer and use it in GitHub Desktop.
const highlightText = (str, match) => {
if (!str) return null;
if (!match) return str;
const regex = new RegExp(match, 'mig');
return `>${str}<`.replace(/>[^<]+</gmi, (match) => match.replace(regex, '[$]')).slice(1, -1);
};
console.log(highlightText('lorem 0 erty o', 'o'));
console.log(highlightText('<p class="lorem">lorem ipsum dolor sit amet</p>', 'o'));
// l[$]rem 0 erty [$]
// <p class="lorem">l[$]rem ipsum d[$]l[$]r sit amet</p>
// https://jsfiddle.net/aShulz/7dgjn51c/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment