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
string.match(regular expression);
Example
Let's find a regular expression match and put it into capturing groups:
let 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:
'12:34'
'12'
'34'
Example
Let's get an array of substrings
consisting of the letters 'a':
let str = 'a aa aaa aaaa';
let res = str.match(/a+/g);
console.log(res);
The code execution result:
['a', 'aa', 'aaa', 'aaaa']