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/15/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 character class includes:|,\,{,},(,),[,],^,$,+,*,?, and.. The$&in the replacement string refers to the matched character, so each one gets a backslash prepended. -
Second replacement (
/-/g→'\\x2d'): Escapes the hyphen-using a hexadecimal escape sequence (\x2d) instead of a simple backslash. According to the comment in [index.js:L7-L8], this is done because "a simple backslash escape when it's always valid" isn't sufficient for hyphens—the hexadecimal form is needed to avoid issues with Unicode patterns' stricter grammar and PCRE compatibility, as verified by the tests in [test.js:L10-L15].
FOLLOW_UPS:
- What characters are considered RegExp special?
- Why does hyphen use hex encoding instead of backslash?
- Can this escape strings for character classes safely?
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.