JavaScript RegExp exec()
Syntax & Examples
RegExp.exec() method
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.
Syntax of RegExp.exec()
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.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
str | required | The string against which to match the regular expression. |
Return Type
RegExp.exec() returns value of type Array
.
✐ Examples
1 Using exec() to find a match in a string
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,
- We create a RegExp object
regex
with the pattern/hello/
. - We use the
exec()
method to search for the pattern in the string'hello world'
. - The result is stored in the variable
result
and we log it to the console.
JavaScript Program
const regex = /hello/;
const result = regex.exec('hello world');
console.log(result);
Output
[ 'hello', index: 0, input: 'hello world', groups: undefined ]
2 Using exec() with a global pattern
In JavaScript, we can use the exec()
method with a global pattern to find multiple matches in a string.
For example,
- We create a RegExp object
regex
with the global pattern/\d+/g
to match one or more digits. - We use the
exec()
method in a loop to find all matches in the string'123 456 789'
. - Each match is logged to the console.
JavaScript Program
const regex = /\d+/g;
let result;
while ((result = regex.exec('123 456 789')) !== null) {
console.log(result);
}
Output
[ '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 ]
3 Using exec() to extract groups from a match
In JavaScript, we can use the exec()
method to extract groups from a matched string.
For example,
- We create a RegExp object
regex
with the pattern/(\w+)\s(\w+)/
to match two words separated by a space. - We use the
exec()
method to search for the pattern in the string'hello world'
. - The result is stored in the variable
result
and we log the matched groups to the console.
JavaScript Program
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'
Output
hello world hello world
Summary
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.