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.

JavascriptSecurity Boundaries

Code

javascriptsnippet
12 lines
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 early throw when 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

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.