RepoPilot

Show me the actual regex implementation that escapes special characters.

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

Question

Show me the actual regex implementation that escapes special characters.

RepoPilot

Here's the regex implementation that escapes special characters in this library:

[index.js:L9-L10]

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

The implementation uses two separate replace operations:

  1. First replace (/[|\\{}()[\]^$+*?.]/g): Escapes the main RegExp special characters by prepending a backslash (\) to each one. This covers: |, \, {, }, (, ), [, ], ^, $, +, *, ?, and .

  2. Second replace (/-/g): Escapes the hyphen character as \x2d (hexadecimal escape) instead of a simple backslash. This is done because a simple backslash escape for hyphens can cause issues in certain contexts like PCRE (Perl Compatible Regular Expressions) and with Unicode patterns, as explained in the test cases [test.js:L10-L20].

The function also includes input validation [index.js:L2-L4] to ensure the argument is actually a string, throwing a TypeError otherwise.

FOLLOW_UPS:

  • Why does the hyphen use hex escape instead of backslash?
  • What special characters does this library handle?
  • How are edge cases like \0 or \c affected?

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.