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/6/2026
The actual regex implementation is in [index.js:L8-L11]:
return string
.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&')
.replace(/-/g, '\\x2d');
This implementation uses two regex replacements:
-
First replacement
[|\\{}()[\]^$+*?.]/g— Escapes the common RegExp special characters by prefixing them with a backslash (\\$&). The character class matches:|(alternation)\(backslash){}(quantifier braces)()(grouping parentheses)[](character class brackets)^(anchor/negation)$(end anchor)+*?.(quantifiers and literal dot)
-
Second replacement
/-/g— Escapes hyphens using\x2d(hex escape) instead of a simple backslash. This is done for compatibility with PCRE and Unicode flag patterns, as shown in the test cases [test.js:L10-L20].
The function also includes type checking to ensure the input is a string [index.js:L2-L4].
FOLLOW_UPS:
- Why does hyphen use
\x2dinstead of backslash? - What RegExp characters are NOT escaped by this function?
- How does this differ from native
RegExp.escape()?
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.