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 8/1/2026
The regex implementation is in [index.js:L9-L10]:
return string
.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&')
.replace(/-/g, '\\x2d');
This uses two replacement operations:
-
First replace
[|\\{}()[\]^$+*?.]/g— Escapes the main RegExp special characters by adding a backslash before each one. The character class includes:|,\,{,},(,),[,],^,$,+,*,?, and.. The\\$&replacement inserts a backslash before the matched character. -
Second replace
/-/g— Escapes the hyphen character as\x2d(hex escape) rather than a simple backslash. This is done to maintain compatibility with PCRE (Perl-Compatible Regular Expressions) and the Unicode flag, as the test cases verify [test.js:L10-L18].
The function first validates the input is a string [index.js:L2-L4], then applies these two replacements to safely escape all special characters.
FOLLOW_UPS:
- What characters are considered RegExp special characters?
- Why is hyphen escaped differently than other characters?
- What is the purpose of the
\xnnescape format?
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.