jsguides

String.prototype.match()

str.match(regexp)

The match() method searches a string using a regular expression and returns an array of matches, or null if no match is found. The return format depends on whether the /g (global) flag is present in the regex.

Without /g, match() returns a single match array that includes the full match at index 0, any capture groups at subsequent indices, and additional properties index (position of the match), input (the original string), and groups (named capture groups or undefined). With /g, it returns a simple array of all matched substrings with no capture group information.

Syntax

str.match(regexp)

Parameters

ParameterTypeDescription
regexpRegExpA regular expression. If a non-RegExp is passed, it’s implicitly converted with new RegExp(regexp).

Return value

An Array with the match details, or null if there was no match. With the /g flag, returns an array of all matched strings. Without /g, returns an array with the first match plus capture groups and metadata.

Examples

Basic usage

const text = "The quick brown fox jumps over the lazy dog";

// Simple word search
console.log(text.match(/fox/));
// ['fox', index: 16, input: 'The quick brown fox...', groups: undefined]

// Find all occurrences (with /g flag)
console.log(text.match(/o/g));
// ['o', 'o', 'o', 'o']

// No match returns null
console.log(text.match(/cat/));
// null

Always check for null before accessing match results, since accessing properties on null throws a TypeError.

The basic usage shows simple word searches and the difference between a single match array and a global match array. When you need to extract structured pieces of a match — like pulling year, month, and day from a date string — capture groups let you label those pieces inside the regex itself.

Working with capture groups

const dates = "2026-03-09, 2025-12-25";

// Extract year, month, day using capture groups
const regex = /(\d{4})-(\d{2})-(\d{2})/;
const result = dates.match(regex);

console.log(result[0]);  // '2026-03-09'
console.log(result[1]);  // '2026'
console.log(result[2]);  // '03'
console.log(result[3]);  // '09'

Without the /g flag, capture groups appear at result[1], result[2], etc. With /g, capture groups are discarded — use matchAll() if you need both the global flag and capture groups.

Numeric indices are fragile — adding or removing a capture group shifts every index after it. Named capture groups solve this by letting you refer to matched content by a descriptive label that stays correct even when you reorganize the pattern.

Named capture groups

const log = "2026-03-09 14:30:45 [INFO] Server started";

// Named capture groups (ES2018+)
const pattern = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
const result = log.match(pattern);

console.log(result.groups.year);  // '2026'
console.log(result.groups.month); // '03'
console.log(result.groups.day);   // '09'

Named groups make the code self-documenting and let you access matches by descriptive names rather than fragile numeric indices.

The examples above focus on the mechanics of matching — how to get results and how to read them. The next section shifts to practical tasks you will encounter in real code: validating input formats and extracting structured data from text.

Common patterns

Validating input

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

console.log(isValidEmail("user@example.com")); // true
console.log(isValidEmail("invalid"));         // false

For validation that only needs a yes/no answer, test() is the leaner choice — it stops at the first match and returns a boolean directly, avoiding the array allocation that match() would perform. If you need to count matches or work with their content, match() is the right tool. Which one you reach for depends on whether the return value shapes the rest of your logic: a boolean avoids null checks entirely.

Extracting all URLs from text

const html = 'Visit https://example.com or http://docs.example.com today!';
const urlRegex = /https?:\/\/[^\s]+/g;

const urls = html.match(urlRegex);
console.log(urls);
// ['https://example.com', 'http://docs.example.com']

The global flag turns match() into a simple array of matched substrings — no capture groups, no index positions, no input property. For cases where you need all that detail across every match, the matchAll() method was introduced in ES2020 to fill that gap. The comparison below shows when to use each.

match() vs matchAll()

Featurematch()matchAll()
ReturnsArray or nullIterator
Capture groups with /gNot accessibleAccessible
/g flag requiredNoYes (always)
MemoryFull array upfrontLazy iterator

Use matchAll() when you need all matches and their capture groups. Use match() for simpler cases where you either need just match strings (with /g) or a single match with groups (without /g).

When to Choose match()

match() is a good default when you want either one detailed match or a simple list of matched substrings. It keeps the regular expression logic in one place and avoids the extra iterator handling that matchAll() introduces. For validation, extraction, and quick searches, match() is often the shortest readable option. The key is to remember how the /g flag changes the shape of the result so you do not accidentally expect capture groups when they are not there.

Guarding Against null

Because match() returns null on failure, every consumer should treat the result as optional. That is especially important when you immediately index into the result or access groups. A small guard, optional chaining, or a fallback array can keep the code safe without making it noisy. If your logic depends on guaranteed matches, it is usually better to validate first and handle the failure path explicitly.

See Also