Literal Characters and Escaping Special Characters
You'll learn how to match exact text in regular expressions and handle characters that have special meanings.
The Core Idea
When you write a regular expression, most characters match themselves literally. The pattern /cat/ matches the exact string "cat". Simple!
But regular expressions have metacharacters—special symbols like ., *, +, and ? that perform actions instead of matching themselves. The dot . matches any character, not an actual period. If you want to match these special characters literally, you must escape them with a backslash \.
Think of escaping like putting quotation marks around a word when you're talking about the word itself. "Run!" means execute, but "'Run!' is a verb" treats it as literal text.
Matching Literal Text
const pattern = /hello/;
pattern.test("hello world"); // true
pattern.test("Hello world"); // false (case-sensitive)
The Problem with Metacharacters
const dotPattern = /3.14/;
dotPattern.test("3.14"); // true
dotPattern.test("3X14"); // true — oops! Dot matched 'X'
Escaping with Backslashes
To match a literal period (or any metacharacter), prefix it with \:
const escapedPattern = /3\.14/;
escapedPattern.test("3.14"); // true
escapedPattern.test("3X14"); // false — now only real periods match
Common characters that need escaping: . * + ? ^ $ { } [ ] ( ) | \
const questionPattern = /What\?/;
questionPattern.test("What?"); // true
questionPattern.test("Whatx"); // false
Key Takeaway: Literal characters match themselves exactly, but special regex metacharacters like ., *, +, and ? must be escaped with a backslash \ when you want to match them as literal text rather than use their special meaning.