matchAll() method returns an iterator of results after matching a string against a regular expression.
The syntax of the
matchAll() method is:
str is a string.
matchAll() method takes a single parameter:
- regex - A regular expression object (Argument is implicitly converted to
regexif it is a non-
regexobject does not have the
TypeErrorwill be thrown.
gflag is for global search which means this flag indicates that we test the regular expression against all the matches in the string.
matchAll() Return Value
- Returns an iterator containing the matches including the capturing groups.
Note: The returned iterator's each item will have the following additional properties:
- groups- An object of named capturing groups having keys as the names and values as the captured matches.
- index- The index of search where the result was found.
- input - A copy of the search string.
Example 1: Using matchAll() Method
In the above example, we have defined a regular expression regex with the
/g flag. We have then invoked the
matchAll() method in sentence.
sentence.matchAll(regex) matches the sentence string against the pattern that has-
'Java' along with any number of characters from a to z.
The method found two matches-
'Java' for the given regex.
Note: The resulting output from the
matchAll() method is in object so we have used
Array.from(result) to convert it to array.
Example 2: Case Sensitive regex in matchAll()
The regular expression(regex) is case sensitive. We can use the
i flag to make it case insensitive in the
matchAll() method. For example:
// string definition const bio = "His name is Albert and albert likes to code."; // pattern having 'albert' or 'Albert' const regex = /albert/gi;// finding 'albert' or 'Albert' in the string const result = bio.matchAll(regex);console.log(Array.from(result));
[ [ 'Albert', index: 13, input: 'His name is Albert and albert likes to code.', groups: undefined ], [ 'albert', index: 24, input: 'His name is Albert and albert likes to code.', groups: undefined ] ]
Here, we have used
i in regex along with
/albert/g) which makes it case insensitive. So the method returns array with two iterators with found matches-