RegExp method matchAll() in Javascript
The RegExp method [@@matchAll]() used to match specified string against regular expression. It specify how String instance method match() should behave with the given regular expression. It returns an iterable iterator (which is not restartable) of matches. The iterable item is an array with the same value which is returned by RegExp intance method exec().
Syntax
 1 regexp[Symbol.matchAll](<string>)
string : a string to search matches using regular expression
RegExp literal method matchAll()
 1 class CustomRegExp extends RegExp {
 2   [Symbol.matchAll](string) {
 3     const matches = RegExp.prototype[Symbol.matchAll].call(this, string);
 4     return matches ? Array.from(matches) : null;
 5   }
 6 }
 7 const format = new CustomRegExp ('-[0-9]+', 'g');
 8 const date = '2015-01-26';
 9 
 10 console.log("Does date matches the format :");
 11 for(match of  date.matchAll(format)) {
 12     console.log(match);
 13 }
In the above example, a CustomRegExp class is define by extending a RegExp which returns either iterable object or null by validating string against the regular expression. An instance of custom class is created by specifying an regex.
A matchAll() method called using string literal and by specifying a format object which will prints result on console.
Output
 1 Does date matches the format :
 2 [ '-01', index: 4, input: '2015-01-26', groups: undefined ]
 3 [ '-26', index: 7, input: '2015-01-26', groups: undefined ]

Example with index position

Example
 1 const regex = /[a-c]/g; // regex literal
 2 regex.lastIndex = 1; // reseting lastIndex to start next match
 3 const str = "abc";
 4 
 5 let matches = str.matchAll(regex);
 6 Array.from(matches).forEach(match => {
 7    console.log(match, ", Occurrence at :", match.index); 
 8 });
In the above example, a regex is define with regex literals and set lastIndex to 1. A matchAll() function called that returns an object that converted to array and iterated using forEach() method by specifying a callback function. A callback function prints an element and index position where occurrence present.
Output
 1 [ 'b', index: 1, input: 'abc', groups: undefined ] , Occurrence at : 1
 2 [ 'c', index: 2, input: 'abc', groups: undefined ] , Occurrence at : 2
Privacy Policy
Terms of Service
Disclaimer
Contact us
About us