Sometimes, we want to match multiple occurrences with a regex in JavaScript similar to PHP’s preg_match_all().
In this article, we’ll look at how to match multiple occurrences with a regex in JavaScript similar to PHP’s preg_match_all().
How to match multiple occurrences with a regex in JavaScript similar to PHP’s preg_match_all()?
To match multiple occurrences with a regex in JavaScript similar to PHP’s preg_match_all(), we can use the string matchAll
method.
For instance, we write
const regexp = /(?:&|&)?([^=]+)=([^&]+)/g;
const str = "1111342=Adam%20Franco&348572=Bob%20Jones";
for (const match of str.matchAll(regexp)) {
const [full, key, value] = match;
console.log(key, value);
}
to call str.matchAll
to match the regex for a query string.
We use a for of loop to get all the match
es.
In the loop, we get the full
string match and the key
and value
of the query string from the match.
Conclusion
To match multiple occurrences with a regex in JavaScript similar to PHP’s preg_match_all(), we can use the string matchAll
method.