Skip to content

Instantly share code, notes, and snippets.

@bloodyowl
Created September 2, 2015 12:11
Show Gist options
  • Save bloodyowl/c84dbf36fe51aa1df7fa to your computer and use it in GitHub Desktop.
Save bloodyowl/c84dbf36fe51aa1df7fa to your computer and use it in GitHub Desktop.
escapeRE for string templates
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