RegExp.prototype[@@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.
let re = /[0-9]+/g;
let str = '2016-01-02';
let 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) {
let result = RegExp.prototype[Symbol.match].call(this, str);
if (!result) return null;
return {
group(n) {
return result[n];
}
};
}
}
let re = new MyRegExp('([0-9]+)-([0-9]+)-([0-9]+)');
let str = '2016-01-02';
let 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 |
---|
ECMAScript Language Specification # sec-regexp.prototype-@@match |
Browser compatibility
Report problems with this compatibility data on GitHubdesktop | mobile | server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
@@match | ChromeFull support50 | EdgeFull support13 | FirefoxFull support49 | Internet ExplorerNo supportNo | OperaFull support37 | SafariFull support10 | WebView AndroidFull support50 | Chrome AndroidFull support50 | Firefox for AndroidFull support49 | Opera AndroidFull support37 | Safari on iOSFull support10 | Samsung InternetFull support5.0 | DenoFull support1.0 | Node.jsFull support6.0.0 |
Legend
- Full support
- Full support
- No support
- No support
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.