JavaScript Regular Expressions

Pattern matching and text processing made easy

🔍 What are Regular Expressions?

Regular Expressions (RegExp) are patterns used to match character combinations in strings. They're powerful tools for searching, replacing, and validating text in JavaScript.


// Simple RegExp example
let pattern = /hello/;
let text = "hello world";
console.log(pattern.test(text)); // true
                                    

Output:

true

Key RegExp Concepts

🎯

Pattern Matching

Find specific patterns in text

let pattern = /cat/;
console.log(pattern.test("I have a cat")); // true
🔄

Text Replacement

Replace text using patterns

let text = "Hello World";
let result = text.replace(/World/, "JavaScript");
console.log(result); // "Hello JavaScript"

Validation

Check if text matches a format

let emailPattern = /\w+@\w+\.\w+/;
console.log(emailPattern.test("[email protected]")); // true
🔍

Text Extraction

Extract specific parts of text

let text = "Phone: 123-456-7890";
let numbers = text.match(/\d+/g);
console.log(numbers); // ["123", "456", "7890"]

🔹 Creating Regular Expressions

There are two ways to create RegExp in JavaScript:

🔸 Literal Notation (Recommended)

// Using forward slashes
let pattern1 = /hello/;
let pattern2 = /\d+/; // matches one or more digits
let pattern3 = /[a-z]/i; // matches any letter, case insensitive

🔸 Constructor Function

// Using RegExp constructor
let pattern1 = new RegExp("hello");
let pattern2 = new RegExp("\\d+"); // note the double backslash
let pattern3 = new RegExp("[a-z]", "i");

💡 When to use each method:

  • Literal notation: When pattern is known at compile time
  • Constructor: When pattern is dynamic or comes from variables

🔹 Basic Pattern Matching

Let's start with simple pattern matching examples:

// Exact match
let pattern = /cat/;
console.log(pattern.test("I have a cat")); // true
console.log(pattern.test("I have a dog")); // false

// Case sensitive by default
let pattern2 = /Cat/;
console.log(pattern2.test("I have a cat")); // false
console.log(pattern2.test("I have a Cat")); // true

// Finding matches
let text = "The cat sat on the mat";
let matches = text.match(/cat/);
console.log(matches[0]); // "cat"

Output:

true
false
false
true
"cat"

🔹 Common Use Cases

Here are practical examples of RegExp usage:

🔸 Email Validation

function isValidEmail(email) {
    let pattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return pattern.test(email);
}

console.log(isValidEmail("[email protected]")); // true
console.log(isValidEmail("invalid-email"));    // false

🔸 Phone Number Formatting

function formatPhone(phone) {
    let cleaned = phone.replace(/\D/g, ''); // remove non-digits
    let pattern = /(\d{3})(\d{3})(\d{4})/;
    return cleaned.replace(pattern, '($1) $2-$3');
}

console.log(formatPhone("1234567890")); // "(123) 456-7890"

🔸 Extract Numbers

let text = "I have 5 cats and 3 dogs";
let numbers = text.match(/\d+/g);
console.log(numbers); // ["5", "3"]

🧠 Test Your Knowledge

Which method tests if a string matches a RegExp pattern?