How do you use the exec() method in JavaScript RegExp?

The exec() method is a built-in function in JavaScript that is used to match a regular expression against a specified string.

It returns an array containing the matched substring(s) if a match is found, otherwise it returns null. The exec() method is used in combination with the RegExp constructor to create a regular expression object.

Basic Usage of exec():

The basic syntax for using the exec() method is as follows:

let regex = /pattern/;
let str = "string";

let result = regex.exec(str);

In the above code snippet, we first create a regular expression object using the RegExp constructor and assign it to the regex variable. We then create a string and assign it to the str variable. Finally, we call the exec() method on the regex object, passing the str variable as its argument. The result of the exec() method is then assigned to the result variable.

Here is an example that demonstrates the basic usage of the exec() method:

let regex = /hello/;
let str = "hello world";

let result = regex.exec(str);

console.log(result);

Output:

[ 'hello', index: 0, input: 'hello world', groups: undefined ]

In the above code snippet, the regular expression /hello/ matches the substring "hello" in the string "hello world". The exec() method returns an array containing the matched substring "hello", the index of the first character of the match in the input string(0), the input string itself ("hello world"), and undefined for the groups property since we did not use any named capturing groups in our regular expression.

Matching Multiple Substrings with exec():

The exec() method can also be used to match multiple substrings in a string using the g (global) flag in the regular expression. When the g flag is used, the exec() method will match all occurrences of the regular expression in the input string.

Here is an example that demonstrates how to match multiple substrings with the exec() method:

let regex = /o/g;
let str = "hello world";

let result;
while ((result = regex.exec(str)) !== null) {
  console.log(`Found '${result[0]}' at index ${result.index}`);
}

Output:

Found 'o' at index 4
Found 'o' at index 7

In the above code snippet, we create a regular expression /o/g with the g flag to match all occurrences of the letter "o" in the input string "hello world". We then use a while loop to iterate through all the matches using the exec() method. The exec() method returns an array containing the matched substring "o", the index of the first character of the match in the input string, and the input string itself. The loop continues until there are no more matches and the exec() method returns null.

Thank you for reading, and let’s have conversation with each other

Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.

Read more: