Explain Regular Expressions in JavaScript. Provide examples of common patterns and use cases.

3 minintermediatejavascriptes6regularexpressionsexamples

Quick Answer

Regular expressions are patterns used to match character combinations in strings.

Detailed Answer

Regular expressions are patterns used to match character combinations in strings.

Basic Syntax:

// Literal notation
const regex = /pattern/flags;

// Constructor notation
const regex = new RegExp('pattern', 'flags');

// Common flags
const regex = /hello/gi; // g = global, i = case-insensitive

Common Patterns:

// Email validation
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
console.log(emailRegex.test('user@example.com')); // true

// Phone number (US format)
const phoneRegex = /^\(\d{3}\) \d{3}-\d{4}$/;
console.log(phoneRegex.test('(555) 123-4567')); // true

// URL validation
const urlRegex = /^https?:\/\/[\w\-]+(\.[\w\-]+)+([\w\-\.,@?^=%&:\/~\+#]*[\w\-\@?^=%&\/~\+#])?$/;
console.log(urlRegex.test('https://www.example.com')); // true

// Password (8+ chars, 1 uppercase, 1 lowercase, 1 number)
const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d@$!%*?&]{8,}$/;
console.log(passwordRegex.test('Password123')); // true

String Methods:

const text = 'Hello World! Hello JavaScript!';

// test() - returns boolean
const regex = /hello/i;
console.log(regex.test(text)); // true

// exec() - returns match details or null
const match = regex.exec(text);
console.log(match); // ['Hello', index: 0, input: 'Hello World! Hello JavaScript!']

// match() - returns array of matches
const matches = text.match(/hello/gi);
console.log(matches); // ['Hello', 'Hello']

// replace() - replaces matches
const newText = text.replace(/hello/gi, 'Hi');
console.log(newText); // 'Hi World! Hi JavaScript!'

// search() - returns index of first match
const index = text.search(/world/i);
console.log(index); // 6

// split() - splits string by pattern
const words = text.split(/\s+/);
console.log(words); // ['Hello', 'World!', 'Hello', 'JavaScript!']

Common Use Cases:

// Extract data from strings
const text = 'Contact: John Doe (555) 123-4567, jane@example.com';
const phoneRegex = /\(\d{3}\) \d{3}-\d{4}/g;
const emailRegex = /[^\s@]+@[^\s@]+\.[^\s@]+/g;

const phones = text.match(phoneRegex); // ['(555) 123-4567']
const emails = text.match(emailRegex); // ['jane@example.com']

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

console.log(formatPhoneNumber('5551234567')); // '(555) 123-4567'

// Validate and sanitize input
function sanitizeInput(input) {
  return input
    .replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '') // Remove script tags
    .replace(/[<>]/g, ''); // Remove angle brackets
}

// Extract URLs from text
function extractUrls(text) {
  const urlRegex = /https?:\/\/[^\s]+/g;
  return text.match(urlRegex) || [];
}