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/29/2026
The actual regex implementation is in [index.js:L9-L10]:
return string
.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&')
.replace(/-/g, '\\x2d');
This implementation uses two sequential regex replacements:
-
First replace (
/[|\\{}()[\]^$+*?.]/g): Escapes the characters| \ { } ( ) [ ] ^ $ + * ? .by prefixing them with a backslash (\\$&). This handles most RegExp special characters. -
Second replace (
/-/g→'\\x2d'): Escapes the hyphen-using hex escape notation (\x2d) instead of a simple backslash. According to the comment in [index.js:L7-L8], this approach is used "when the simpler form would be disallowed by Unicode patterns' stricter grammar."
The tests in [test.js:L11-L14] confirm this special handling for hyphens to maintain compatibility with PCRE and the Unicode flag.
FOLLOW_UPS:
- Why does the hyphen use hex escape instead of backslash?
- Which characters are considered RegExp special characters?
- How does this handle Unicode characters like emoji?
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.