How does this function validate its input — does it throw on bad arguments?
How does this function validate its input — does it throw on bad arguments?
About sindresorhus/escape-string-regexp · 2 messages · last activity 7/20/2026
Yes, it does basic input validation. The function checks that the argument is a string, and throws a TypeError if not:
export default function escapeStringRegexp(string) {
if (typeof string !== 'string') {
throw new TypeError('Expected a string');
}
...
[index.js:L1-L4]
This is a simple runtime typeof check — if you pass anything other than a string (e.g., a number, object, undefined, null), it throws TypeError: Expected a string immediately, before any escaping logic runs.
There's no test in test.js that explicitly exercises this error path (the visible tests only cover valid string inputs — special characters and the - handling, [test.js:L1-L24]), but the check is present in the source itself.
On the TypeScript side, the type definition just declares the expected signature:
export default function escapeStringRegexp(string: string): string;
[index.d.ts:L16-L17]
So under TypeScript, passing a non-string would be caught at compile time; the runtime TypeError guard in index.js is what protects plain JavaScript callers.
FOLLOW_UPS:
- What characters does the regex actually escape?
- Why is
-handled differently with\x2d? - Are there tests for invalid (non-string) input?
Want to ask your own question?
Open chat for sindresorhus/escape-string-regexpPublic 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.