Skip to content

Instantly share code, notes, and snippets.

@itashdv
Created April 4, 2021 12:27
Show Gist options
  • Save itashdv/efdc4811108942469a89243ac569a65c to your computer and use it in GitHub Desktop.
Save itashdv/efdc4811108942469a89243ac569a65c to your computer and use it in GitHub Desktop.
Escaping special characters in "new RegExp" constructor
function highlightText(text, search) {
RegExp.escape = function(string) {
return string.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
console.log(new RegExp(RegExp.escape(search), "gi"));
const html = text.replace(
new RegExp(RegExp.escape(search), "gi"),
(match) => `<span class=${styles.highlight}>${match}</span>`,
);
return html;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment