What edge cases are covered in the tests, especially around hyphens?
What edge cases are covered in the tests, especially around hyphens?
About sindresorhus/escape-string-regexp · 2 messages · last activity 9/1/2026
The test suite covers two important edge cases related to hyphens:
-
PCRE compatibility [test.js:L10-L14]: The test verifies that hyphens are escaped as
\x2d(hex escape) rather than a simple backslash escape. This is necessary because PCRE (Perl Compatible Regular Expressions) has stricter rules about hyphen placement in character classes. -
Unicode flag compatibility [test.js:L16-L20]: A separate test confirms that the escaped hyphen works correctly when the RegExp is used with the
u(Unicode) flag. This ensures the escaping strategy doesn't break under Unicode mode's stricter grammar rules.
The general case of special characters is also tested [test.js:L3-L7], which covers the standard regex metacharacters: \ ^ $ * + ? . ( ) | { } [ ]. These use simple backslash escaping (\$&).
The dual-escape strategy is explained in the implementation [index.js:L9-L10]: the code uses a simple backslash escape for most special characters, but switches to \x2d for hyphens specifically because the simpler form would be disallowed by Unicode patterns' stricter grammar rules.
This design reflects the README's note [readme.md:L24-L28] that minimal escaping is done, relying on developers to insert escaped strings at safe positions in a RegExp, though edge cases like hyphens require special handling.
FOLLOW_UPS:
- Why does hyphen need hex escaping instead of backslash?
- What other characters have special escaping rules?
- How are Unicode patterns' grammar rules stricter?
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.