RepoPilot

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

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

Question

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

RepoPilot

Yes, the function performs a basic type check before doing any escaping.

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

export default function escapeStringRegexp(string) {
	if (typeof string !== 'string') {
		throw new TypeError('Expected a string');
	}
	...
}

[index.js:L1-L4]

So if you call it with anything other than a string (e.g. a number, object, undefined, etc.), it immediately throws a TypeError with the message 'Expected a string', rather than attempting to coerce the value or silently failing.

This is also reflected in the type declaration, which types the parameter as string:

export default function escapeStringRegexp(string: string): string;

[index.d.ts:L16]

So at the TypeScript level, passing a non-string would be a compile-time type error, while at runtime (e.g. from plain JS or after bypassing type checks), the explicit typeof guard is what enforces the check and throws.

There's no other argument validation beyond this — once the type check passes, it proceeds directly to the two .replace() calls that do the actual escaping [index.js:L6-L10].

FOLLOW_UPS:

  • What characters does the regex [|\\{}()[\]^$+*?.] escape?
  • Why is - escaped separately with \x2d?
  • What does the test suite cover for this function?

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.