-
-
Save bloodyowl/c84dbf36fe51aa1df7fa to your computer and use it in GitHub Desktop.
escapeRE for string templates
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
const merge = (strings, substitutions) => | |
strings.reduceRight((acc, string, index) => [string, substitutions[index], ...acc], []) | |
const escapeRE = (strings, ...substitutions) => | |
merge(strings, [...substitutions, ""]).map((s) => String(s).replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("") | |
console.log(escapeRE`^foo[foo](${ "(" + 1 + 2 })`) // "\^foo\[foo\]\(\(12\)" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment