The String match() method
By Flavio Copes
Learn how the JavaScript match() method runs a regular expression against a string and returns an array of matches and capture groups, or null if none match.
The match() method runs a regular expression against a string. It returns an array describing the match, or null if the regex matches nothing.
You call it on the string, passing the regex:
'Hi Flavio'.match(/avio/)
// [ 'avio' ]
Tip: try these examples yourself in my regex tester — it highlights matches and capture groups live.
What the returned array contains
Without the g flag, match() stops at the first match. The first element of the array is the matched text, followed by one element per capture group:
'123s'.match(/^(\d{3})(\w+)$/)
// [ '123s', '123', 's' ]
The whole match is '123s', the first group captured '123', the second 's'.
The array also carries extra properties. index tells you where the match starts in the string, and input is the original string:
const result = 'Hi Flavio'.match(/avio/)
result.index //5
result.input //'Hi Flavio'
More examples
'Test 123123329'.match(/\d+/)
// [ '123123329' ]
'hey'.match(/(hey|ho)/)
// [ 'hey', 'hey' ]
'123456789'.match(/(\d)+/)
// [ '123456789', '9' ]
That last one surprises people: a repeated capture group keeps only the last thing it captured, here the 9.
A (?:...) group is non-capturing: it matches, but doesn’t show up in the results:
'123s'.match(/^(\d{3})(?:\s)(\w+)$/)
// null
'123 s'.match(/^(\d{3})(?:\s)(\w+)$/)
// [ '123 s', '123', 's' ]
And \b matches a word boundary, useful to avoid matching inside longer words:
'I saw a bear'.match(/\bbear/) // [ 'bear' ]
'I saw a beard'.match(/\bbear/) // [ 'bear' ]
'I saw a beard'.match(/\bbear\b/) // null
'cool_bear'.match(/\bbear\b/) // null
The last two return null because “bear” is not a whole word there.
Finding all matches with the g flag
Add the g flag and match() returns every match, as an array of plain strings:
'my car is faster than your car'.match(/car/g)
// [ 'car', 'car' ]
With g you lose the capture groups and the index property. If you need the groups or the position for every match, use matchAll() instead. It returns an iterator of full match objects, one per match.
The pitfall: null
When nothing matches, match() returns null, not an empty array. Grabbing the first element without checking crashes:
'hey'.match(/\d+/)[0]
//TypeError: Cannot read properties of null (reading '0')
Use optional chaining to stay safe:
'hey'.match(/\d+/)?.[0]
//undefined
To know more about Regular Expressions, see my Regular Expressions tutorial.