RepoPilot

Show me the actual regex implementation that escapes special characters.

About sindresorhus/escape-string-regexp · 2 messages · last activity 7/27/2026

Question

Show me the actual regex implementation that escapes special characters.

RepoPilot

The regex implementation that escapes special characters is in [index.js:L9-L10]:

return string
	.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&')
	.replace(/-/g, '\\x2d');

This uses two separate regex replacements:

  1. First replacement (/[|\\{}()[\]^$+*?.]/g): Escapes the core RegExp special characters by prefixing them with a backslash. The character class includes:

    • | (alternation)
    • \ (backslash)
    • {} (quantifiers)
    • () (groups)
    • [] (character classes)
    • ^ (anchor)
    • $ (anchor)
    • +*?. (quantifiers and wildcards)
  2. Second replacement (/-/g): Escapes the hyphen (-) as \x2d (hex escape) instead of a simple backslash escape. This is done for compatibility with PCRE and Unicode patterns, as documented in the tests [test.js:L10-L13] and [test.js:L15-L20].

The function is minimal and intentional—it only escapes what's necessary, expecting developers to insert the escaped string at safe positions in a RegExp.

FOLLOW_UPS:

  • Why does the hyphen use \x2d instead of \-?
  • What characters are NOT escaped by this function?
  • Can this handle emoji and Unicode safely?

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.