JavaScript:match() 和 matchAll() 之间的区别

如果可以实现记得点赞分享,谢谢老铁~

在这里插入图片描述

String.prototype.match()

String.prototype.match() 是 JavaScript 中的一种方法,它返回与正则表达式匹配字符串的结果数组。

返回的结果在很大程度上取决于使用 global(g) 标志。如果使用 ag 标志,我们将获得所有结果,但不捕获组。

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

另一方面,如果我们不使用 g 标志,我们将仅获得第一个完整的匹配项,但具有相关的捕获组。

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

String.prototype.matchAll()

这就是 matchAll() 的用武之地。 String.prototype.matchAll() 返回一个迭代器,该迭代器根据正则表达式返回所有匹配的组,包括捕获组。matchAll() 的主要原因之一是改进了对捕获组的访问。

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

迭代器为每次匹配生成一个数组,因此它也适用于 for…of 循环。

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

matchAll()的正则表达式需要有ag标志,否则会抛出错误。

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

如果没有匹配项,则 match() 方法返回 null。

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

同一示例中的 matchAll() 方法返回一个空的可迭代对象。

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

结论

正如我们所看到的,match() 和 matchAll() 之间的差异并不小,这意味着 matchAll() 绝不可以被视为 match() 的替代品。

String.prototype.matchAll() 是 ES2020 中的一个新功能,它处于最后的第 4 阶段。不过,对于某些浏览器,您将需要使用 polyfill。您可以使用 Babel 或npm 包

猜你喜欢

转载自blog.csdn.net/Gas_station/article/details/131829408