RepoPilot

Show me the actual regex implementation that escapes special characters.

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

Question

Show me the actual regex implementation that escapes special characters.

RepoPilot

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

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

This uses two regex replacements:

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

  2. Second replacement (/-/g'\\x2d'): Escapes hyphens as hexadecimal escape sequences (\x2d). This special handling is necessary because hyphens have different meaning in different regex contexts and need escaping that's compatible with PCRE and Unicode flag patterns.

The function first validates the input is a string [index.js:L2-L4], then applies these two replacements to escape all special characters.

FOLLOW_UPS:

  • Why is the hyphen escaped differently as \x2d?
  • What characters are considered RegExp special characters?
  • How does this differ from native RegExp.escape()?

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.