Skip to content

escapeRegExp

Escapes the 12 ECMAScript regex metacharacters (. * + ? ^ $ { } ( ) | [ ] \) so the string can be safely interpolated into a RegExp. Prevents regex injection when user input is used in a pattern.

import { escapeRegExp } from "1o1-utils";
import { escapeRegExp } from "1o1-utils/escape-reg-exp";
function escapeRegExp({ str }: EscapeRegExpParams): string
NameTypeRequiredDescription
strstringYesThe string to escape

string

escapeRegExp({ str: "[hello](world)" });
// => "\\[hello\\]\\(world\\)"
const re = new RegExp(escapeRegExp({ str: userInput }), "i");
re.test(text);
  • Throws if str is not a string.
  • Returns "" for empty string.
  • Strings with no special characters are returned unchanged.
  • Unicode characters are preserved.

escape regex, regex injection, escape pattern, safe regex

I'm using 1o1-utils (npm: https://www.npmjs.com/package/1o1-utils, GitHub: https://github.com/pedrotroccoli/1o1-utils, LLM context: https://pedrotroccoli.github.io/1o1-utils/llms.txt). Show me how to use escapeRegExp to safely build a RegExp from user input