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 6/1/2026
The actual regex implementation is in [index.js:L9-L10]:
return string
.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&')
.replace(/-/g, '\\x2d');
This uses two replacement operations:
-
First replace
[|\\{}()[\]^$+*?.]/g- Escapes most RegExp special characters by adding a backslash (\\$&) before them. This handles:|,\,{,},(,),[,],^,$,+,*,?,. -
Second replace
/-/g→\\x2d- Escapes the hyphen character using a Unicode escape sequence (\x2d) instead of a simple backslash. This is done separately because the hyphen requires special handling to be compatible with PCRE and Unicode regex patterns, as documented in the tests [test.js:L10-L15].
The function first validates that the input is a string [index.js:L2-L4], then applies these two regex replacements in sequence.
FOLLOW_UPS:
- Why is the hyphen escaped differently as
\x2d? - What characters are considered RegExp special characters?
- Can this escape strings for use in character classes?
Want to ask your own question?
Open chat for sindresorhus/escape-string-regexp →Public 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.