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/18/2026
The regex implementation is in [index.js:L9-L10]:
return string
.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&')
.replace(/-/g, '\\x2d');
This implementation uses two separate regex replacements:
-
First replacement
[|\\{}()[\]^$+*?.]/g— escapes the main RegExp special characters by replacing them with a backslash-escaped version using\\$&(where$&refers to the matched character). -
Second replacement
/-/g— escapes the hyphen character specifically as\\x2d(hexadecimal escape) instead of a simple backslash. According to the test comments in [test.js:L10-L11], this approach is "compatible with PCRE" and [test.js:L17-L21] ensures compatibility with the Unicode flag.
The characters escaped in the first pass are: |, \, {, }, (, ), [, ], ^, $, +, *, ?, and .
FOLLOW_UPS:
- Why does hyphen need hexadecimal escaping instead of backslash?
- What characters are considered RegExp special characters?
- How does this compare to RegExp.escape() natively?
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.