Escape Strings for Literal Regular Expression Matching
Escape every regular-expression metacharacter so user input can be matched literally, with a helper that rejects stateful flags.
Code
export function escapeRegExp(input) {
if (typeof input !== "string") throw new TypeError("input must be a string");
return input.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
export function literalRegExp(input, flags = "") {
if (typeof flags !== "string") throw new TypeError("flags must be a string");
if (/[gy]/.test(flags)) {
throw new RangeError("stateful flags g and y are not allowed");
}
return new RegExp(escapeRegExp(input), flags);
}What the code does
Escape Strings for Literal Regular Expression Matching is built around the functions escapeRegExp and literalRegExp.
Invalid states are rejected up front: it throws TypeError and RangeError instead of continuing with bad data.
What comes back is a new object, not a reference to anything passed in.
What to watch for
- The guard
typeof input !== "string"short-circuits the flow with an earlythrowwhen its condition holds.
Using it
The entry-point signature is export function escapeRegExp(input)
escapeRegExp is what another module would consume; nothing else here is load-bearing for callers.
Key statements
if (typeof input !== "string") throw new TypeError("input must be a string");
if (typeof flags !== "string") throw new TypeError("flags must be a string");
throw new RangeError("stateful flags g and y are not allowed");
Interactive Tools for This Topic
Regular Expression TesterTest regular expressions against sample text with live match highlighting, capture group extraction, and flags support for global, case-insensitive, and multiline modes.Regex Escape GeneratorEscape plain text so it can be embedded safely in a JavaScript RegExp, covering all metacharacters like dots, brackets, braces, and backslashes.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.
FAQ
- Does `escapeRegExp` modify its input?
- No — a new value is constructed for the result and the arguments are never written to.
- Is there a failure path for bad input?
- Validation comes first — `TypeError` and `RangeError` marks the failure at `typeof input !== "string"`, before any partial work happens.
- Is the dependency story complicated?
- Not at all: zero dependencies, so there is nothing to version or audit. The file defines `escapeRegExp`, `literalRegExp` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.