JS 正则表达式 [@@matchAll]()

🌙
手机阅读
本文目录结构

 [@@matchAll]方法返回对字符串使用正则表达式的所有匹配项。

{{EmbedInteractiveExample(“pages/js/regexp-prototype-@@matchall.html”)}}

The source for this interactive example is stored in a GitHub repository. If you’d like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

语法

regexp[Symbol.matchAll](str)

参数

str

一个String的匹配对象。

返回值

一个迭代器

描述

本方法在String.prototype.matchAll()中被内部调用。例如,以下两个示例返回相同的结果。

'abc'.matchAll(/a/);

/a/[Symbol.matchAll]('abc');

本方法用于自定义RegExp子类中的匹配行为。

示例

直接调用

本方法的使用方法几乎与String.prototype.matchAll()相同,除了this 的不同以及参数顺序的的差异。

var re = /[0-9]+/g;
var str = '2016-01-02';
var result = re[Symbol.matchAll](str);

console.log(Array.from(result, x => x[0]));  
// ["2016", "01", "02"]

在子类中使用@@matchAll

RegExp的子类可以重写[@@matchAll]()方法来修改默认行为。例如,返回一个Array而不是iterator

class MyRegExp extends RegExp {
  [Symbol.matchAll](str) {
    var result = RegExp.prototype[Symbol.matchAll].call(this, str);
    if (!result) { 
      return null;
    } else {
      return Array.from(result);
    }
  }
}

var re = new MyRegExp('([0-9]+)-([0-9]+)-([0-9]+)', 'g');
var str = '2016-01-02|2019-03-07';
var result = str.matchAll(re);
console.log(result[0]); // [ "2016-01-02", "2016", "01", "02" ]
console.log(result[1]); // [ "2019-03-07", "2019", "03", "07" ]

相关链接

AXIHE / 精选资源

浏览全部教程

面试题

学习网站

前端培训
自己甄别

前端书籍

关于朱安邦

我叫 朱安邦,阿西河的站长,在杭州。

以前是一名平面设计师,后来开始接接触前端开发,主要研究前端技术中的JS方向。

业余时间我喜欢分享和交流自己的技术,欢迎大家关注我的 Bilibili

关注我: Github / 知乎

于2021年离开前端领域,目前重心放在研究区块链上面了

我叫朱安邦,阿西河的站长

目前在杭州从事区块链周边的开发工作,机械专业,以前从事平面设计工作。

2014年底脱产在老家自学6个月的前端技术,自学期间几乎从未出过家门,最终找到了满意的前端工作。更多>

于2021年离开前端领域,目前从事区块链方面工作了