JavaScript: Difference between match() and matchAll()

If it can be achieved, remember to like and share, thank you~

Insert image description here

String.prototype.match()

String.prototype.match() is a method in JavaScript that returns a resulting array of strings that match a regular expression.

The results returned depend heavily on the use of the global(g) flag. If we use the ag flag, we will get all the results but not the capturing group.

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 only get the first complete match, but with the associated capturing group.

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 matching groups based on a regular expression, including capturing groups. One of the main reasons for matchAll() is to improve access to capturing 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 generates an array for each match, so it also works with for...of loops.

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"]

The regular expression of matchAll() needs to have the ag 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 is no match, the match() method returns null.

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

The 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 {  }

in conclusion

As we can see, the difference between match() and matchAll() is not trivial, which means that matchAll() should never be considered a replacement for match().

String.prototype.matchAll() is a new feature in ES2020 and is in the final stage 4. However, for some browsers you will need to use a polyfill. You can use Babel or npm packages .

Guess you like

Origin blog.csdn.net/Gas_station/article/details/131829408