The matchAll() method in JavaScript returns an iterator containing all matches of a string against a regular expression. Each match is returned as an array, including capturing groups if present.
Syntax: string.matchAll(regexp)
- regexp: A regular expression object or a string representing a regular expression pattern.
Example:
let str = "The rain in Spain falls mainly in the plain";
let regexp = /ain/g;
let matchesIterator = str.matchAll(regexp);
for (let match of matchesIterator) {
console.log(match);
}
Output:
["ain", index: 5, input: "The rain in Spain falls mainly in the plain", groups: undefined]
["ain", index: 14, input: "The rain in Spain falls mainly in the plain", groups: undefined]
["ain", index: 25, input: "The rain in Spain falls mainly in the plain", groups: undefined]
Explanation:
- We have a string str containing "The rain in Spain falls mainly in the plain".
- We use matchAll(/ain/g) to find all occurrences of "ain" in the string.
- The method returns an iterator containing all matches found, each represented as an array with additional information like the index of the match and the input string.
We can iterate over the iterator to access each match individually.
Code Compiler Link: https://app.singhteekam.in/codecompiler/