JavaScript(JS) string method - matchall

The matchAll() method is a string method introduced in ECMAScript 2019 that is used to search for all occurrences of a pattern in a string and return an iterator of matches. The pattern can be either a regular expression or a string.

Here is the syntax for the matchAll() method:

r‮ot refe‬:theitroad.com
str.matchAll(regexp)

Here, str is the original string you want to search in, and regexp is the regular expression or string pattern you want to search for.

The matchAll() method returns an iterator of all matches found in the string. If no matches are found, an empty iterator is returned. Each item in the iterator is an array containing the matched substring and any captured groups specified in the regular expression pattern.

Here is an example of using the matchAll() method with a regular expression pattern:

let str = "The quick brown fox jumps over the lazy dog.";
let pattern = /[A-Z]/g;
let result = str.matchAll(pattern);
for (let match of result) {
  console.log(match[0]);
}

In the example above, the matchAll() method searches the str for any uppercase letters and returns an iterator of all matches found. The regular expression pattern /[A-Z]/g matches any uppercase letter and the g flag specifies a global search that finds all matches. The for...of loop iterates over the iterator and prints each matched substring found in the string, which are "T", "B", and "F".

Here is an example of using the matchAll() method with a string pattern:

let str = "The quick brown fox jumps over the lazy dog.";
let pattern = "quick";
let result = str.matchAll(pattern);
for (let match of result) {
  console.log(match[0]);
}

In the example above, the matchAll() method searches the str for the string "quick" and returns an iterator of all matches found. Since there is only one match, the resulting iterator contains the substring "quick". The for...of loop iterates over the iterator and prints the single match found in the string.