JavaScript Regular Expressions
Match patterns in strings.
Creating Regex
let pattern = /hello/; // Literal notation
let pattern = new RegExp("hello"); // Constructor (for dynamic patterns)
let pattern = /hello/gi; // With flags
Basic Methods
let pattern = /hello/i;
pattern.test("Hello World"); // true (boolean)
"Hello World".match(pattern); // ["Hello"]
"Hello World".search(pattern); // 0 (index)
"Hello World".replace(pattern, "Hi"); // "Hi World"
Character Classes
/\d+/.test("123"); // true (digits)
/\w+/.test("hello"); // true (word characters)
/\s+/.test(" "); // true (whitespace)
/.llo/.test("hello"); // true (any character)
Uppercase variants match inverses: \D (non-digit), \W (non-word), \S (non-whitespace).
Quantifiers
/ab*/.test("a"); // true (zero or more b's)
/ab+/.test("a"); // false (one or more b's)
/ab?/.test("a"); // true (zero or one b)
/a{2,4}/.test("aaa"); // true (2 to 4 a's)
Anchors
/^hello/.test("hello world"); // true (start of string)
/hello$/.test("say hello"); // false (not at end)
/^hello$/.test("hello"); // true (exact match)
Remember: Use ^ and $ for validation to ensure the entire string matches.
Groups and Alternation
/(cat|dog)/.test("I have a cat"); // true (OR)
let match = "123-456-7890".match(/(\d{3})-(\d{3})-(\d{4})/);
console.log(match[1]); // "123" (capturing group)
Flags
| Flag | Meaning |
|---|---|
g |
Global (all matches) |
i |
Case-insensitive |
m |
Multiline (^/$ match lines) |
s |
Dotall (. matches newlines) |
Email Validation
let emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
emailPattern.test("[email protected]"); // true
emailPattern.test("invalid"); // false
Phone Validation
let phonePattern = /^\+?[\d\s-]{10,}$/;
phonePattern.test("+1-555-123-4567"); // true
phonePattern.test("123"); // false
Password Validation
let passPattern = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/;
passPattern.test("MyP@ss123"); // true
passPattern.test("weak"); // false
Uses lookaheads (?=...) to require lowercase, uppercase, digit, and min 8 chars.
Extracting Data
let text = "Date: 2024-01-15";
let match = text.match(/(\d{4})-(\d{2})-(\d{2})/);
console.log(match[1], match[2], match[3]); // "2024" "01" "15"
Best Practices
- Test thoroughly — Edge cases matter
- Use character classes — More readable
- Use anchors — For exact matching
- Keep patterns simple — Document complex ones
Common Mistakes
- Forgetting
^and$— Partial matches - Not using
gflag — Only finds first match - Overcomplicating — Keep patterns simple
- Not escaping special chars —
. * + ? ( ) [ ] { } \ ^ $ |