String#matchAll
(see the Stage 3 Draft / December 7, 2018 proposal), simplifies acccess to all groups in the match object (mind that Group 0 is the whole match, while further groups correspond to the capturing groups in the pattern):
With
matchAll
available, you can avoid thewhile
loop andexec
with/g
... Instead, by usingmatchAll
, you get back an iterator which you can use with the more convenientfor...of
, array spread, orArray.from()
constructs
This method yields a similar output to Regex.Matches
in C#, re.finditer
in Python, preg_match_all
in PHP.
See a JS demo (tested in Google Chrome 73.0.3683.67 (official build), beta (64-bit)):
var myString = "key1:value1, key2-value2!!@key3=value3";_x000D_
var matches = myString.matchAll(/(\w+)[:=-](\w+)/g);_x000D_
console.log([...matches]); // All match with capturing group values
_x000D_
The console.log([...matches])
shows
You may also get match value or specific group values using
let matchData = "key1:value1, key2-value2!!@key3=value3".matchAll(/(\w+)[:=-](\w+)/g)_x000D_
var matches = [...matchData]; // Note matchAll result is not re-iterable_x000D_
_x000D_
console.log(Array.from(matches, m => m[0])); // All match (Group 0) values_x000D_
// => [ "key1:value1", "key2-value2", "key3=value3" ]_x000D_
console.log(Array.from(matches, m => m[1])); // All match (Group 1) values_x000D_
// => [ "key1", "key2", "key3" ]
_x000D_
NOTE: See the browser compatibility details.