RepoPilot

Show me the actual regex implementation that escapes special characters.

About sindresorhus/escape-string-regexp · 2 messages · last activity 5/18/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 implementation uses two separate regex replacements:

  1. First replacement [|\\{}()[\]^$+*?.]/g — escapes the main RegExp special characters by replacing them with a backslash-escaped version using \\$& (where $& refers to the matched character).

  2. Second replacement /-/g — escapes the hyphen character specifically as \\x2d (hexadecimal escape) instead of a simple backslash. According to the test comments in [test.js:L10-L11], this approach is "compatible with PCRE" and [test.js:L17-L21] ensures compatibility with the Unicode flag.

The characters escaped in the first pass are: |, \, {, }, (, ), [, ], ^, $, +, *, ?, and .

FOLLOW_UPS:

  • Why does hyphen need hexadecimal escaping instead of backslash?
  • What characters are considered RegExp special characters?
  • How does this compare to RegExp.escape() natively?

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.