match method

The match method returns an array of matches with regular expression. If there are no matches, it will return null. When called without the g modifier, the method returns an array, the zero element of which will contain the found substring, and the remaining elements will contain capturing groups. If the method is called with the g modifier it returns all found matches as an array.

Syntax

javascriptstring.match(regular expression);

Example

Let's find a regular expression match and put it into capturing groups:

javascriptlet str = '12:34';
let res = str.match(/(\d+):(\d+)/);

console.log(res[0]); // found
console.log(res[1]); // 1st capturing group
console.log(res[2]); // 2nd capturing group

The code execution result:

javascript'12:34'
'12'
'34'

Example

Let's get an array of substrings consisting of the letters 'a':

javascriptlet str = 'a aa aaa aaaa';
let res = str.match(/a+/g);

console.log(res);

The code execution result:

javascript['a', 'aa', 'aaa', 'aaaa']

See also

  • the test method
    that checks a string
  • the matchAll method
    that searches for all matches in a string
  • the exec method
    that performs a sequential search
  • the replace method
    that performs search and replacement
  • the search method
    that performs a search
  • the split method
    that splits a string