Over 10 years we help companies reach their financial and branding goals. Engitech is a values-driven technology agency dedicated.

Gallery

Contacts

411 University St, Seattle, USA

engitech@oceanthemes.net

+1 -800-456-478-23

Blog

String.prototype.match()

String.prototype.match() is a method in JavaScript that returns an array of results matching a string against a regular expression.

Returned results depend a lot on using the global(g) flag. If a g flag is used we will get all results but without capturing groups.

const str = "ReguralExpresion RegExr";
const regex = /E(x)([a-z])/g;
const match = str.match(regex); //Array ["Exp", "Exr"]

On the other hand, if we don’t use the g flag we will get only the first complete match but with related capturing groups.

const str = "ReguralExpresion RegExr";
const regex = /E(x)([a-z])/;
const match = str.match(regex); //Array ["Exp", "x", "p"]

String.prototype.matchAll()

This is where matchAll() comes in. String.prototype.matchAll() returns an iterator that returns all matched groups against a regular expression, including capturing groups. One of the main reasons for matchAll() is the improved access to capture groups.

const str = "ReguralExpresion RegExr";
const regex = /E(x)([a-z])/g;
const match = str.matchAll(regexp);
Array.from(match, (res) => console.log(res));
//Array ["Exp", "x", "p"]
//Array ["Exr", "x", "r"]

The iterator produces an array for every match so it works great with for…of loops too.

const str = "ReguralExpresion RegExr";
const regex = /E(x)([a-z])/g;
const match = str.matchAll(regex);
for (const m of match) {
  console.log(m);
}
//Array ["Exp", "x", "p"]
//Array ["Exr", "x", "r"]

A regular expression for matchAll() needs to have a g flag, otherwise, an error will be thrown.

const str = "ReguralExpresion RegExr";
const regex = /E(x)([a-z])/;
const match = str.matchAll(regex);
//Error: String.prototype.matchAll called with a non-global RegExp argument

If there are no matches, match() method returns null.

const str = "ReguralExpresion RegExr";
const regex = /E(m)([a-z])/g;
const match = str.match(regex); //null

matchAll() method in the same example returns an empty iterable object.

const str = "ReguralExpresion RegExr";
const regex = /E(m)([a-z])/g;
const match = str.matchAll(regex); //Object {  }

Conclusion

As we can see the difference between match() and matchAll() is not small which means that matchAll() by no means can be looked as a replacement for a match().

String.prototype.matchAll() is a new feature in ES2020, it is in final Stage 4. Still, for some browsers, you will need to use polyfills. You can use Babel or npm package.


Launching a new JavaScript project? Need help on an existing project? Work with us

Marija Ziterbart

Marija Ziterbart

Software engineer with a proven record of designing and implementing complex software systems. Marija is also the CTO of The Lowdown.