RepoPilot

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

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

Question

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

RepoPilot

Yes — the function performs an explicit type check before doing any escaping.

At the very start of the function body, it checks that 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 escapeStringRegexp() with anything that isn't a JS string (e.g., a number, undefined, an object, etc.), it throws a TypeError with the message 'Expected a string' rather than attempting to process it or silently coercing it.

If the input passes that check, it proceeds to the actual escaping logic:

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

[index.js:L7-L10]

This does two .replace() passes:

  1. Escapes the RegExp special characters | \ { } ( ) [ ] ^ $ + * ? . with a leading backslash.
  2. Escapes - specifically using the \x2d hex-escape form instead of a plain backslash — this is called out in the tests as being done for compatibility with both PCRE and the Unicode (u) flag [test.js:L11-L23].

There's no other validation beyond the type check — it doesn't, for example, validate string length, encoding, or contents; any string (including empty strings, strings with astral/unicode characters, etc.) is accepted and passed through the two replace operations.

The TypeScript type declaration also reflects this contract at the type level, declaring the parameter as string and the return type as string [index.d.ts:L16], and the test-d.ts file confirms the return type is string via tsd [index.test-d.ts:L1-L5].

FOLLOW_UPS:

  • Why is - escaped differently from other special characters?
  • What Node.js versions does this package support?
  • Is there a CommonJS version of this package available?

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.