Unescaped Special Characters
What you'll learn: How forgetting to escape regex special characters can break your patterns in unexpected ways.
Regular expressions use certain characters as metacharacters with special meanings: . + * ? | ( ) [ ] { } ^ $ \. When you want to match these characters literally in your text, you must escape them with a backslash (\). Forgetting to do so is one of the most common regex bugs.
The Problem
Imagine you want to match the literal string "3.99" (a price). If you write:
const pattern = /3.99/;
pattern.test("3.99"); // true
pattern.test("3x99"); // true — OOPS!
The dot is a metacharacter meaning "any character," so it matches both the period and the letter "x". This wasn't your intent!
The Solution
Escape the dot with a backslash:
const pattern = /3\.99/;
pattern.test("3.99"); // true
pattern.test("3x99"); // false — correct!
Real-World Example
A common mistake when matching file extensions:
// WRONG: Matches "file.txt" but also "filextxt"
const wrong = /file.txt$/;
// CORRECT: Only matches "file.txt"
const correct = /file\.txt$/;
Think of It Like This
In English, quotation marks let you say about a word: The word "run" has three letters. In regex, the backslash lets you talk about a metacharacter instead of using its special power.
When building patterns with special characters, always ask: "Do I want the special meaning or the literal character?" If literal, escape it.
Key Takeaway: Always escape special characters (. + * ? | ( ) [ ] { } ^ $ \) with a backslash when you want to match them literally, or your pattern will behave unexpectedly.