RepoPilot

How does this function validate its input — does it throw on bad arguments?

About sindresorhus/escape-string-regexp · 2 messages · last activity 9/1/2026

Question

How does this function validate its input — does it throw on bad arguments?

RepoPilot

Yes — the function performs a simple type check before doing any escaping work.

At the top of escapeStringRegexp, it checks whether the input is a string:

if (typeof string !== 'string') {
	throw new TypeError('Expected a string');
}

[index.js:L2-L4]

If string is anything other than a JavaScript string primitive (e.g., a number, object, undefined, null, array, etc.), it throws a TypeError with the message 'Expected a string' immediately, before reaching the .replace() calls. There's no coercion attempt (like calling .toString() on the input) — it's a strict typeof check.

This validation behavior isn't covered by an explicit test in [test.js:L1-L24] (the existing tests only exercise valid string inputs and the escaping logic itself), but it is documented in the type declaration [index.d.ts:L16-L17], which types the parameter as string, and enforced at runtime in the implementation.

If the input passes validation, execution proceeds to the two-step escaping:

  1. .replace(/[|\\{}()[\]^$+*?.]/g, '\\$&') — escapes RegExp metacharacters with a simple backslash.
  2. .replace(/-/g, '\\x2d') — escapes - using a \xnn hex escape instead of a backslash, for compatibility with both PCRE-style regex and the Unicode (u) flag grammar, as explained in the inline comment [index.js:L6-L7] and exercised by the tests in [test.js:L11-L23].

FOLLOW_UPS:

  • Why is - escaped differently from other characters?
  • What does the regex package alternative offer?
  • Are there known edge cases with \0 or \c escaping?

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.