W3cubDocs

/JavaScript

regExp.@@match

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

Syntax

regexp[Symbol.match](str)

Parameters

str
A String that is a target of the match.

Return value

An Array containing the entire match result and any parentheses-captured matched results, or null if there were no matches.

Description

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

Browser compatibilityUpdate compatibility data on GitHub

Desktop
Chrome Edge Firefox Internet Explorer Opera Safari
Basic support Yes Yes 49 No Yes Yes
Mobile
Android webview Chrome for Android Edge Mobile Firefox for Android Opera for Android iOS Safari Samsung Internet
Basic support Yes Yes Yes 49 Yes Yes Yes
Server
Node.js
Basic support 6.0.0

See also

© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@match