Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

RegExp.prototype[@@match]()

这篇翻译不完整。请帮忙从英语翻译这篇文章

The [@@match]() method retrieves the matches when matching a string against a regular expression.

语法

regexp[Symbol.match](str)

参数

str
match 的目标参数是String

返回值

match 方法会返回一个数组,它包括整个正则表达式匹配到的所有字符和通过捕获组捕获到的结果,如果没有匹配到返回null

描述

This method is called internally in String.prototype.match(). For example, the following two examples return same result.

'abc'.match(/a/);

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

This method exists for customizing match behavior within RegExp subclasses.

Examples

Direct call

This method can be used in almost the same way as String.prototype.match(), except the different this and the different arguments order.

var re = /[0-9]+/g;
var str = '2016-01-02';
var result = re[Symbol.match](str);
console.log(result);  // ["2016", "01", "02"]

Using @@match in subclasses

Subclasses of RegExp can override the [@@match]() method to modify the default behavior.

class MyRegExp extends RegExp {
  [Symbol.match](str) {
    var result = RegExp.prototype[Symbol.match].call(this, str);
    if (!result) return null;
    return {
      group(n) {
        return result[n];
      }
    };
  }
}

var re = new MyRegExp('([0-9]+)-([0-9]+)-([0-9]+)');
var str = '2016-01-02';
var result = str.match(re); // String.prototype.match calls re[@@match].
console.log(result.group(1)); // 2016
console.log(result.group(2)); // 01
console.log(result.group(3)); // 02

Specifications

Specification Status Comment
ECMAScript 2015 (6th Edition, ECMA-262)
RegExp.prototype[@@match]
Standard Initial defintion.
ECMAScript 2017 Draft (ECMA-262)
RegExp.prototype[@@match]
Draft  

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) 49 (49) 未实现 (Yes) (Yes)
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (Yes) (Yes) 49.0 (49) 未实现 (Yes) (Yes)

See also

文档标签和贡献者

 此页面的贡献者: boatlet
 最后编辑者: boatlet,