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 7/20/2026
Here's the regex implementation that escapes special characters in this library:
[index.js:L9-L10]
return string
.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&')
.replace(/-/g, '\\x2d');
The implementation uses two separate replace operations:
-
First replace (
/[|\\{}()[\]^$+*?.]/g): Escapes the main RegExp special characters by prepending a backslash (\) to each one. This covers:|,\,{,},(,),[,],^,$,+,*,?, and. -
Second replace (
/-/g): Escapes the hyphen character as\x2d(hexadecimal escape) instead of a simple backslash. This is done because a simple backslash escape for hyphens can cause issues in certain contexts like PCRE (Perl Compatible Regular Expressions) and with Unicode patterns, as explained in the test cases [test.js:L10-L20].
The function also includes input validation [index.js:L2-L4] to ensure the argument is actually a string, throwing a TypeError otherwise.
FOLLOW_UPS:
- Why does the hyphen use hex escape instead of backslash?
- What special characters does this library handle?
- How are edge cases like
\0or\caffected?
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.