Regular Expressions (RegExp) Basics
Regular expressions (regex) are patterns for matching text — validating emails, phone numbers, searching/replacing text, and extracting data. Every developer needs to understand basic patterns.
RegExp Basics
- Literal — /pattern/flags: /hello/i (case-insensitive match for 'hello')
- test() — Returns true/false: /hello/.test('Hello World') → true with /i flag
- match() — Returns matches: 'Hello 123'.match(/\d+/) → ['123']
- replace() — Replace matches: 'Hello'.replace(/hello/i, 'Hi') → 'Hi'
- Common patterns — \d (digit), \w (word char), \s (whitespace), . (any char)
- Quantifiers — + (1+), * (0+), ? (0 or 1), {n} (exactly n), {n,m} (n to m)
- Anchors — ^ (start), $ (end): /^hello$/i matches only 'hello'
- Flags — g (global/all), i (case-insensitive), m (multiline)
RegExp Code
// Basic matching
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
console.log(emailRegex.test("user@email.com")); // true
console.log(emailRegex.test("invalid-email")); // false
// Phone number (10 digits)
const phoneRegex = /^\d{10}$/;
console.log(phoneRegex.test("9876543210")); // true
console.log(phoneRegex.test("123")); // false
// Extract numbers from string
const text = "I have 3 cats and 5 dogs";
const numbers = text.match(/\d+/g);
console.log(numbers); // ["3", "5"]
// Replace
const cleaned = "Hello World".replace(/\s+/g, " ");
console.log(cleaned); // "Hello World"
// Password validation (8+ chars, 1 letter, 1 number)
const strongPassword = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d@$!%*#?&]{8,}$/;
console.log(strongPassword.test("pass1234")); // true
console.log(strongPassword.test("password")); // false (no number)
console.log(strongPassword.test("12345678")); // false (no letter)
// Extract all words
const words = "Hello, World! How are you?".match(/\w+/g);
console.log(words); // ["Hello", "World", "How", "are", "you"]
// Real-world: sanitize input
function sanitize(input) {
return input.replace(/[<>&"']/g, ""); // remove HTML special chars
}
console.log(sanitize('<script>alert("XSS")</script>'));Tip
Tip
Use the regex test() method for validation checks and match()/matchAll() for extraction. For complex patterns, build regex step by step and test with regex101.com — it explains each part of your pattern visually.
Quantifiers, character classes, anchors, and flags
Common Mistake
Warning
Not escaping special regex characters when searching for literal text. Dots, brackets, parentheses have special meaning in regex. Use string.includes() for simple text searches instead of regex when you don't need pattern matching.
Practice Task
Note
Regex practice: (1) Validate an email format with regex. (2) Extract all numbers from a string using matchAll. (3) Create a password strength checker that verifies uppercase, lowercase, number, and special character requirements.
Quick Quiz
Key Takeaways
- Regular expressions (regex) are patterns for matching text — validating emails, phone numbers, searching/replacing text, and extracting data.
- Literal — /pattern/flags: /hello/i (case-insensitive match for 'hello')
- test() — Returns true/false: /hello/.test('Hello World') → true with /i flag
- match() — Returns matches: 'Hello 123'.match(/\d+/) → ['123']