exec method
The exec method performs a
string search using a given
regular expression.
The found substring and its capturing
groups are returned as a result. In
this case, each subsequent call to
this method will start the search
from the place where the previous
found substring ended. If no match
is found, it returns null.
Syntax
javascriptregular expression.test(string);
Example
We test the method:
javascriptlet str = '12 34 56';
let reg = /\d+/g;
let res1 = reg.exec(str);
console.log(res1);
let res2 = reg.exec(str);
console.log(res2);
let res3 = reg.exec(str);
console.log(res3);
let res4 = reg.exec(str);
console.log(res4);
The code execution result:
javascript[12]
[34]
[56]
null
Example
Let's use the method in a loop:
javascriptlet str = '12 34 56';
let reg = /\d+/g;
let res;
while (res = reg.exec(str)) {
console.log(res);
}
The code execution result:
javascript[12]
[34]
[56]
Example
Found matches can be decomposed into capturing groups:
javascriptlet str = '12 34 56';
let reg = /(\d)(\d)/g;
let res;
while (res = reg.exec(str)) {
console.log(res);
}
The code execution result:
javascript[12, 1, 2]
[34, 3, 4]
[56, 5, 6]
Example
Using the lastIndex property,
you can set the position from which
to start the search:
javascriptlet str = '12 34 56';
let reg = /\d+/g;
reg.lastIndex = 2;
let res1 = reg.exec(str)
console.log(res1);
let res2 = reg.exec(str)
console.log(res2);
The code execution result:
javascript[34]
[56]
Example
Using the y modifier, you can
fix the search start position:
javascriptlet str = '12 34 56';
let reg = /\d+/y;
reg.lastIndex = 2;
let res1 = reg.exec(str)
console.log(res1);
let res2 = reg.exec(str)
console.log(res2);
The code execution result:
javascriptnull
[12]