RepoPilot

Show me the actual regex implementation that escapes special characters.

About sindresorhus/escape-string-regexp · 2 messages · last activity 9/1/2026

Question

Show me the actual regex implementation that escapes special characters.

RepoPilot

The regex implementation is in [index.js:L9-L10]:

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

This uses two sequential replacements:

  1. First replacement (/[|\\{}()[\]^$+*?.]/g): Escapes the core RegExp special characters by replacing each with a backslash followed by the character itself (\\$&). The character class includes: |, \, {, }, (, ), [, ], ^, $, +, *, ?, and .

  2. Second replacement (/-/g): Escapes the hyphen/dash character using a hex escape sequence (\x2d) instead of a simple backslash. This is done separately because, as noted in the comment at [index.js:L7-L8], the hex escape is needed to be compatible with Unicode patterns' stricter grammar and PCRE (as verified by the test at [test.js:L10-L15]).

The function first validates that the input is a string [index.js:L2-L4], throwing a TypeError if it isn't.

FOLLOW_UPS:

  • Why does the hyphen use hex escape instead of backslash?
  • What RegExp special characters are not escaped here?
  • How does this handle emoji and Unicode characters?

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.