Created
April 4, 2021 12:27
-
-
Save itashdv/efdc4811108942469a89243ac569a65c to your computer and use it in GitHub Desktop.
Escaping special characters in "new RegExp" constructor
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
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