match()

ES3+

Retrieves the result of matching a string against a regular expression.

Syntax

string.match(regexp)

Parameters

regexp RegExp

A regular expression object

Return Value

Array | null

An Array of matches, or null if no match was found

Examples

JavaScript
const str = 'The rain in Spain';
console.log(str.match(/ain/g));
console.log(str.match(/xyz/));
Output:
// ['ain', 'ain'] null

📌 When to Use

Use match() when you need to find pattern occurrences and extract them, especially when using capturing groups. For simple existence checks, includes() is faster. For replacements, use replace() directly.

⚠️ Common Mistakes

Forgetting that match() returns null when no match is found - always check before accessing properties or iterating.

Not understanding the difference between global (/g) and non-global matching - global returns all matches, non-global returns first match with capture groups.

Using match() when matchAll() would be better for getting all matches with their capture groups (ES2020+).

✅ Best Practices

Use optional chaining with match(): const result = str.match(/pattern/)?.[0] to safely access the first match.

For extracting multiple parts, use named capture groups: /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/.

When you need both the matched strings and their positions, use matchAll() or repeated exec() calls instead.

⚡ Performance Notes

match() compiles the regex each time if passed as a literal. For repeated matching operations, store the RegExp in a variable. For large texts with complex patterns, consider if simpler string methods might suffice.

🌍 Real World Example

Data Extraction and Validation

match() is powerful for extracting structured data from strings, such as parsing URLs, extracting dates, finding all hashtags in text, or validating format patterns.

// Extract all hashtags from text
function extractHashtags(text) {
  const matches = text.match(/#[\w\u0080-\uFFFF]+/g);
  return matches || [];
}

console.log(extractHashtags('Hello #world! Learn #JavaScript #coding'));
// ['#world', '#JavaScript', '#coding']

// Parse URL components
function parseUrl(url) {
  const pattern = /^(https?:\/\/)?([^\/]+)(\/[^?]*)?(?:\?(.*))?$/;
  const match = url.match(pattern);

  if (!match) return null;

  return {
    protocol: match[1] || 'http://',
    host: match[2],
    path: match[3] || '/',
    query: match[4] || ''
  };
}

console.log(parseUrl('https://example.com/page?id=123'));
// { protocol: 'https://', host: 'example.com', path: '/page', query: 'id=123' }

// Extract date components using named groups
function parseDate(dateString) {
  const pattern = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
  const match = dateString.match(pattern);

  if (!match?.groups) return null;

  return {
    year: parseInt(match.groups.year),
    month: parseInt(match.groups.month),
    day: parseInt(match.groups.day)
  };
}

console.log(parseDate('2024-01-15'));
// { year: 2024, month: 1, day: 15 }

// Validate email format and extract parts
function validateEmail(email) {
  const pattern = /^([a-zA-Z0-9._-]+)@([a-zA-Z0-9.-]+)\.([a-zA-Z]{2,})$/;
  const match = email.match(pattern);

  if (!match) return { valid: false };

  return {
    valid: true,
    username: match[1],
    domain: match[2],
    tld: match[3]
  };
}

console.log(validateEmail('user@example.com'));
// { valid: true, username: 'user', domain: 'example', tld: 'com' }

Related Methods