search

String.prototype.match

Runs a regular expression against the string and returns match information. With the g flag it returns an array of all match strings; without it, an exec-style array with capture groups, index, and input (or null).

str.match(regexp)

Parameters

Parameter Purpose
regexp RegExp to match; a non-RegExp is passed to new RegExp()
returns Array of matches (or capture array) when found; null otherwise

Examples

console.log('hello 123 world 456'.match(/\d+/g));

Prints [ '123', '456' ]

console.log('hello 123'.match(/(\w+)\s(\d+)/)[2]);

Prints '123' (second capture group)

console.log('abc'.match(/z/));

Prints null

console.log('hello'.match(/l/));

Prints [ 'l', index: 2, input: 'hello', groups: undefined ]

Gotcha

Return shape depends on the g flag — an easy source of bugs. Returns null (not []) when nothing matches, so guard before iterating.

Related methods

← All JS string methods · JS array methods