RepoPilot

Show me the actual regex implementation that escapes special characters.

About sindresorhus/escape-string-regexp · 2 messages · last activity 6/1/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 replacement operations:

  1. First replace [|\\{}()[\]^$+*?.]/g - Escapes most RegExp special characters by adding a backslash (\\$&) before them. This handles: |, \, {, }, (, ), [, ], ^, $, +, *, ?, .

  2. Second replace /-/g\\x2d - Escapes the hyphen character using a Unicode escape sequence (\x2d) instead of a simple backslash. This is done separately because the hyphen requires special handling to be compatible with PCRE and Unicode regex patterns, as documented in the tests [test.js:L10-L15].

The function first validates that the input is a string [index.js:L2-L4], then applies these two regex replacements in sequence.

FOLLOW_UPS:

  • Why is the hyphen escaped differently as \x2d?
  • What characters are considered RegExp special characters?
  • Can this escape strings for use in character classes?

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.