JavaScript RegExp Patterns

Building complex pattern matching expressions

🎯 What are RegExp Patterns?

RegExp patterns are combinations of characters, metacharacters, and quantifiers that define search criteria. They allow you to create powerful and flexible text matching rules.


// Simple pattern example
let pattern = /hello/i;
let text = "Hello World";
console.log(pattern.test(text)); // true
                                    

Output:

true

Common Pattern Types

📧

Email Validation

Match valid email addresses

/^[^\s@]+@[^\s@]+\.[^\s@]+$/
📱

Phone Numbers

Match phone number formats

/^$$\d{3}$$\s\d{3}-\d{4}$/
🌐

URLs

Match web addresses

/^https?:\/\/[\w\.-]+/
🔢

Numbers

Match numeric patterns

/^\d+(\.\d{2})?$/

🔹 Email Pattern Example

A comprehensive email validation pattern:

// Email validation pattern
let emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;

// Test different emails
let emails = [
    "[email protected]",
    "[email protected]",
    "invalid.email",
    "user@domain"
];

emails.forEach(email => {
    console.log(`${email}: ${emailPattern.test(email)}`);
});

Output:

[email protected]: true
[email protected]: true
invalid.email: false
user@domain: false

🔹 Phone Number Patterns

Different phone number format patterns:

// Various phone number patterns
let patterns = {
    us: /^$$\d{3}$$\s\d{3}-\d{4}$/,           // (123) 456-7890
    international: /^\+\d{1,3}\s\d{3,14}$/,    // +1 1234567890
    simple: /^\d{3}-\d{3}-\d{4}$/              // 123-456-7890
};

let phones = [
    "(123) 456-7890",
    "+1 1234567890",
    "123-456-7890",
    "123.456.7890"
];

phones.forEach(phone => {
    console.log(`${phone}:`);
    for (let [type, pattern] of Object.entries(patterns)) {
        console.log(`  ${type}: ${pattern.test(phone)}`);
    }
});

Output:

(123) 456-7890:
us: true
international: false
simple: false
+1 1234567890:
us: false
international: true
simple: false

🔹 URL Pattern Matching

Pattern to match and extract URL components:

// URL pattern with groups
let urlPattern = /^(https?):\/\/([^\/\s]+)(\/[^\s]*)?$/;

let urls = [
    "https://www.example.com",
    "http://subdomain.site.org/path/to/page",
    "ftp://invalid.protocol.com",
    "https://domain.com/search?q=test"
];

urls.forEach(url => {
    let match = url.match(urlPattern);
    if (match) {
        console.log(`URL: ${url}`);
        console.log(`Protocol: ${match[1]}`);
        console.log(`Domain: ${match[2]}`);
        console.log(`Path: ${match[3] || '/'}`);
        console.log('---');
    } else {
        console.log(`Invalid URL: ${url}`);
    }
});

Output:

URL: https://www.example.com
Protocol: https
Domain: www.example.com
Path: /
---
URL: http://subdomain.site.org/path/to/page
Protocol: http
Domain: subdomain.site.org
Path: /path/to/page

🔹 Password Strength Pattern

Pattern to validate strong passwords:

// Password strength pattern
// At least 8 chars, 1 uppercase, 1 lowercase, 1 digit, 1 special char
let strongPassword = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/;

let passwords = [
    "Password123!",
    "weakpass",
    "STRONGPASS123!",
    "NoSpecial123",
    "short1!"
];

passwords.forEach(password => {
    let isStrong = strongPassword.test(password);
    console.log(`${password}: ${isStrong ? 'Strong' : 'Weak'}`);
});

Output:

Password123!: Strong
weakpass: Weak
STRONGPASS123!: Strong
NoSpecial123: Weak
short1!: Weak

🧠 Test Your Knowledge

Which pattern matches a valid email address?