Developer Patterns

Regex escaper

Runs in your browser · nothing is uploaded

Local · twelve metacharacters, plus / and -
Advertisement
320 × 100

Escapes every character that means something to the regular-expression engine, so a literal string — a price, a file path, a URL; can be dropped into a pattern and match itself rather than being read as syntax.

How to escape text for a regex

1 Paste the literal text.
2 Copy the escaped version.
3 Drop it into your pattern where the literal belongs.

Twelve characters carry meaning inside a pattern and have to be escaped to match literally: . * + ? ^ $ { } ( ) | [ ] \. A forward slash and a hyphen are added here too; the slash because a pattern written between slashes needs it, the hyphen because inside a character class an unescaped one means a range.

The reason this matters beyond convenience is injection. Building a pattern by concatenating user input is the regex equivalent of building SQL by concatenation: a search box that puts what someone typed straight into a new RegExp can be handed (a+)+$ and made to hang the process. Escaping first removes the syntax and leaves the text. JavaScript has no built-in for this; RegExp.escape was proposed and only recently reached browsers — which is why almost every codebase has its own copy of the same one-line function.

Questions

The twelve metacharacters . * + ? ^ $ { } ( ) | [ ] and the backslash, plus the forward slash and hyphen for safety inside slashes and character classes.

MDN, Regular expressionsECMA-262, RegExp objects
Advertisement
300 × 250
Was this tool any good?
Internal signal only · I use it to find the tools worth rebuilding