Regular Expressions: The Essentials
Regex looks scary but it's incredibly useful. Here are the patterns you'll actually use.
Why Regex
Text matching and transformation. Validation, parsing, search/replace.
The Basics
// Test if pattern matches
/hello/.test("hello world") // true
// Find matches
"hello world".match(/o/g) // ["o", "o"]
// Replace
"hello world".replace(/world/, "regex") // "hello regex"
Character Classes
/[abc]/ // a, b, or c
/[a-z]/ // any lowercase letter
/[A-Z]/ // any uppercase letter
/[0-9]/ // any digit
/[^abc]/ // NOT a, b, or c
// Shortcuts
/\d/ // digit [0-9]
/\w/ // word char [a-zA-Z0-9_]
/\s/ // whitespace
/./ // any character except newline
Quantifiers
/a*/ // 0 or more a's
/a+/ // 1 or more a's
/a?/ // 0 or 1 a
/a{3}/ // exactly 3 a's
/a{2,5}/ // 2 to 5 a's
/a{2,}/ // 2 or more a's
Anchors
/^hello/ // starts with hello
/world$/ // ends with world
/\bword\b/ // word boundary (whole word)
Grouping
/(ab)+/ // one or more "ab"
/hello|world/ // hello OR world
/(hello) (world)/ // capture groups
Practical Examples
Email Validation (simple)
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
emailRegex.test("test@example.com") // true
Phone Number
const phoneRegex = /^\d{3}-\d{3}-\d{4}$/;
phoneRegex.test("123-456-7890") // true
Extract Numbers
"Price: $99.99".match(/\d+\.?\d*/g) // ["99.99"]
Replace Multiple Spaces
"too many spaces".replace(/\s+/g, " ")
// "too many spaces"
Validate Password Strength
// At least 8 chars, 1 uppercase, 1 lowercase, 1 digit
const strongPassword = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/;
Parse URL
const url = "https://example.com/path?query=1";
const urlParts = url.match(/^(https?):\/\/([^\/]+)(\/[^?]*)?\??(.*)$/);
// ["https://example.com/path?query=1", "https", "example.com", "/path", "query=1"]
Flags
/pattern/g // global - find all matches
/pattern/i // case insensitive
/pattern/m // multiline
/pattern/gi // combine flags
Testing Regex
Use regex101.com to build and test patterns interactively.
Tips
1. Start simple, add complexity 2. Test with edge cases 3. Use non-capturing groups `(?:)` when you don't need the capture 4. Be careful with greedy quantifiers (`.*` vs `.*?`) 5. Comment complex regex
Regex is a superpower. Learn the basics and Google the rest.