The exec() method of the RegExp object in JavaScript executes a search for a match in a specified string. This method returns an array containing the matched results, or null if no match is found.
The syntax of RegExp.exec() method is:
exec(str)
This exec() method of RegExp executes a search for a match in its string parameter. Returns an array containing the matched results or null if no match is found.
Parameter | Optional/Required | Description |
---|---|---|
str | required | The string against which to match the regular expression. |
RegExp.exec() returns value of type Array
.
In JavaScript, we can use the exec()
method to find a match in a string. The method returns an array with the matched results.
For example,
regex
with the pattern /hello/
.exec()
method to search for the pattern in the string 'hello world'
.result
and we log it to the console.const regex = /hello/;
const result = regex.exec('hello world');
console.log(result);
[ 'hello', index: 0, input: 'hello world', groups: undefined ]
In JavaScript, we can use the exec()
method with a global pattern to find multiple matches in a string.
For example,
regex
with the global pattern /\d+/g
to match one or more digits.exec()
method in a loop to find all matches in the string '123 456 789'
.const regex = /\d+/g;
let result;
while ((result = regex.exec('123 456 789')) !== null) {
console.log(result);
}
[ '123', index: 0, input: '123 456 789', groups: undefined ] [ '456', index: 4, input: '123 456 789', groups: undefined ] [ '789', index: 8, input: '123 456 789', groups: undefined ]
In JavaScript, we can use the exec()
method to extract groups from a matched string.
For example,
regex
with the pattern /(\w+)\s(\w+)/
to match two words separated by a space.exec()
method to search for the pattern in the string 'hello world'
.result
and we log the matched groups to the console.const regex = /(\w+)\s(\w+)/;
const result = regex.exec('hello world');
console.log(result[0]); // 'hello world'
console.log(result[1]); // 'hello'
console.log(result[2]); // 'world'
hello world hello world
In this JavaScript tutorial, we learned about exec() method of RegExp: the syntax and few working examples with output and detailed explanation for each example.