JavaScript Regular Expressions

JavaScript Regular Expressions

Regular expressions (regex) are powerful patterns for searching and manipulating text. They’re like a mini-language for matching strings. In JavaScript, regex helps with validation, search, and text processing.

What Are Regular Expressions?

Regex patterns describe text patterns. For example:

  • \d matches any digit
  • \w matches any word character
  • + means one or more
  • * means zero or more

Creating Regex

Use regex literals or constructor:

// Literal (recommended for simple patterns)
let pattern = /\d+/;

// Constructor (for dynamic patterns)
let dynamicPattern = new RegExp('\\d+');

Testing for Matches

Use test() to check if a string matches:

let emailPattern = /\w+@\w+\.\w+/;
console.log(emailPattern.test('user@example.com')); // true
console.log(emailPattern.test('invalid-email')); // false

Finding Matches

Use match() to find matches in a string:

let text = 'The year is 2023 and 2024 is next.';
let yearPattern = /\d{4}/g; // g flag for global search
let years = text.match(yearPattern);
console.log(years); // ['2023', '2024']

Replacing Text

Use replace() with regex:

let text = 'Hello, world!';
let newText = text.replace(/world/, 'JavaScript');
console.log(newText); // 'Hello, JavaScript!'

Replace all occurrences:

let text = 'cat, bat, hat';
let newText = text.replace(/at/g, 'op');
console.log(newText); // 'cop, bop, hop'

Common Patterns

Email validation

let emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

Phone number

let phoneRegex = /^\d{3}-\d{3}-\d{4}$/;
console.log(phoneRegex.test('123-456-7890')); // true

Username (letters, numbers, underscore, 3-16 chars)

let usernameRegex = /^[a-zA-Z0-9_]{3,16}$/;

Regex Flags

  • g: Global (find all matches)
  • i: Case insensitive
  • m: Multiline
let text = 'JavaScript is fun\njavascript is powerful';
let pattern = /javascript/gi;
console.log(text.match(pattern)); // ['JavaScript', 'javascript']

Capturing Groups

Use parentheses to capture parts:

let datePattern = /(\d{2})\/(\d{2})\/(\d{4})/;
let dateString = '12/25/2023';
let match = dateString.match(datePattern);
console.log(match[0]); // '12/25/2023' (full match)
console.log(match[1]); // '12' (month)
console.log(match[2]); // '25' (day)
console.log(match[3]); // '2023' (year)

Practical Examples

Extract URLs from text

let text = 'Visit https://example.com and http://test.org';
let urlPattern = /https?:\/\/[^\s]+/g;
let urls = text.match(urlPattern);
console.log(urls); // ['https://example.com', 'http://test.org']

Validate password strength

function isStrongPassword(password) {
  // At least 8 chars, 1 uppercase, 1 lowercase, 1 digit
  let strongPattern = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$/;
  return strongPattern.test(password);
}

console.log(isStrongPassword('Password123')); // true
console.log(isStrongPassword('weak')); // false

Format phone numbers

function formatPhone(phone) {
  let cleaned = phone.replace(/\D/g, ''); // Remove non-digits
  let match = cleaned.match(/^(\d{3})(\d{3})(\d{4})$/);
  if (match) {
    return '(' + match[1] + ') ' + match[2] + '-' + match[3];
  }
  return phone;
}

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

Regex takes practice, but it’s invaluable for text processing. Start with simple patterns and build up.

For more regex tools and testing, sites like regex101.com are helpful.

The MDN RegExp reference has complete documentation.

Last updated on