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.
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/[.*+?^${}()|[\]\\]/gInput
const escape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')Result
Prepends a backslash to every special char in sIn 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
Hex Color Code
Match CSS hex color codes in both 3-digit (#RGB) and 6-digit (#RRGGBB) formats.
/#(?:[0-9a-fA-F]{6}|[0-9a-fA-F]{3})…/gMarkdown Link
Match Markdown links [link text](url) and capture both the display text and the URL.
/\[([^\]]+)\]\(([^)]+)\)/gHTML Tag Matcher
Match paired HTML tags and capture the tag name and inner content using a back-reference.
/<([a-zA-Z][a-zA-Z0-9]*)\b[^>]*>([\…/g