RepoPilot

Show me the actual regex implementation that escapes special characters.

About sindresorhus/escape-string-regexp · 2 messages · last activity 5/25/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 main RegExp special characters by prefixing them with a backslash. The pattern matches: |, \, {, }, (, ), [, ], ^, $, +, *, ?, and .. The \\$& replacement inserts a backslash before each matched character.

  2. Second replacement (/-/g): Escapes the hyphen character using \x2d (a hex escape sequence) instead of a simple backslash. According to the comment in [index.js:L7-L8], this approach is needed because a simple backslash escape would be disallowed by Unicode patterns' stricter grammar, but the hex escape is always valid.

The function also validates input type in [index.js:L2-L4], throwing a TypeError if the argument is not a string.

FOLLOW_UPS:

  • Why does the hyphen use hex escape instead of backslash?
  • What characters are considered RegExp special characters here?
  • How does this handle Unicode characters like emojis?

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.