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);
}Report a problem with this exampleOpens a pre-filled issue on GitHub.