How-to

How to Escape Regex Special Characters

Backslash-escape any of .^$*+?()[]{}|\ to match them literally. When building a regex from user input, use a full-escape helper function.

The characters that need escaping

Outside a character class: . * + ? ^ $ ( ) [ ] { } | \ — all have special meaning. Prefix with \ to match them literally. Inside a character class, most of these lose their meaning; only ] \ ^ and - need escaping in specific positions.

Match a literal period

Try this
/\./

Input

example.com

Result

Match: .

Match a literal plus

Try this
/1 \+ 1/

Input

1 + 1 = 2

Result

Match: 1 + 1

Escaping user input before using it in a regex

If you accept a user string and then search for it with regex (a 'find' feature, say), any regex metachars in their input will misbehave. Escape them first. JavaScript doesn't have a built-in for this — use the snippet below.

Safe regex from user input

Try this
/[.*+?^${}()|[\]\\]/g

Input

const escape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')

Result

Prepends a backslash to every special char in s

In string literals vs. regex literals

Regex literal: /\./ has one backslash. String-built regex: new RegExp('\\.') needs TWO — one for the string escape, one for the regex escape. This trips people up constantly. Prefer regex literals when the pattern is static.

Characters that don't need escaping

Letters, digits, and many punctuation characters (!, @, #, %, comma, semicolon, colon, etc.) have no special regex meaning and can be written as-is. Over-escaping is harmless but obscures intent.

Related patterns

All reference guidesOpen the RegexPro tester →