Show me the actual regex implementation that escapes special characters.
Show me the actual regex implementation that escapes special characters.
About sindresorhus/escape-string-regexp · 2 messages · last activity 7/27/2026
The regex implementation that escapes special characters is in [index.js:L9-L10]:
return string
.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&')
.replace(/-/g, '\\x2d');
This uses two separate regex replacements:
-
First replacement (
/[|\\{}()[\]^$+*?.]/g): Escapes the core RegExp special characters by prefixing them with a backslash. The character class includes:|(alternation)\(backslash){}(quantifiers)()(groups)[](character classes)^(anchor)$(anchor)+*?.(quantifiers and wildcards)
-
Second replacement (
/-/g): Escapes the hyphen (-) as\x2d(hex escape) instead of a simple backslash escape. This is done for compatibility with PCRE and Unicode patterns, as documented in the tests [test.js:L10-L13] and [test.js:L15-L20].
The function is minimal and intentional—it only escapes what's necessary, expecting developers to insert the escaped string at safe positions in a RegExp.
FOLLOW_UPS:
- Why does the hyphen use
\x2dinstead of\-? - What characters are NOT escaped by this function?
- Can this handle emoji and Unicode safely?
Want to ask your own question?
Open chat for sindresorhus/escape-string-regexpPublic Q&A. Generated by RepoPilot from the actual source of sindresorhus/escape-string-regexp. AI answers can be incomplete or stale — verify before relying on them.