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 5/25/2026
The regex implementation is in [index.js:L9-L10]:
return string
.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&')
.replace(/-/g, '\\x2d');
This uses two sequential replacements:
-
First replacement (
/[|\\{}()[\]^$+*?.]/g): Escapes the main RegExp special characters by prefixing them with a backslash. The pattern matches:|,\,{,},(,),[,],^,$,+,*,?, and.. The\\$&replacement inserts a backslash before each matched character. -
Second replacement (
/-/g): Escapes the hyphen character using\x2d(a hex escape sequence) instead of a simple backslash. According to the comment in [index.js:L7-L8], this approach is needed because a simple backslash escape would be disallowed by Unicode patterns' stricter grammar, but the hex escape is always valid.
The function also validates input type in [index.js:L2-L4], throwing a TypeError if the argument is not a string.
FOLLOW_UPS:
- Why does the hyphen use hex escape instead of backslash?
- What characters are considered RegExp special characters here?
- How does this handle Unicode characters like emojis?
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.