Skip to content

Commit

Permalink
[New] Add RegExp.prototype[Symbol.match]
Browse files Browse the repository at this point in the history
  • Loading branch information
ljharb committed Nov 16, 2015
1 parent 28c5032 commit 233ab2a
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 2 deletions.
1 change: 1 addition & 0 deletions README.md
Expand Up @@ -43,6 +43,7 @@ In both browser and node you may also want to include `unorm`; see the [`String.
* `new RegExp`, when given a RegExp as the pattern, will no longer throw when given a "flags" string argument. (requires ES5)
* `RegExp.prototype`:
* `flags` (requires ES5) ([a standalone shim is also available](https://github.com/es-shims/RegExp.prototype.flags))
* `[Symbol.match]` (requires native `Symbol`s)
* `Number`:
* binary and octal literals: `Number('0b1')` and `Number('0o7')`
* `EPSILON`
Expand Down
7 changes: 6 additions & 1 deletion es6-shim.js
Expand Up @@ -550,7 +550,12 @@
}());
if (!symbolMatchExists || stringMatchIgnoresSymbolMatch) {
var symbolMatch = defineWellKnownSymbol('match');

var originalMatch = String.prototype.match;
defineProperty(RegExp.prototype, symbolMatch, function match(string) {
return ES.Call(originalMatch, string, [this]);
});

var matchShim = function match(regexp) {
var O = ES.RequireObjectCoercible(this);
if (regexp !== null && typeof regexp !== 'undefined') {
Expand All @@ -559,7 +564,7 @@
return ES.Call(matcher, regexp, [O]);
}
}
return ES.Call(originalMatch, O, arguments);
return ES.Call(originalMatch, O, [String(regexp)]);
};
overrideNative(String.prototype, 'match', matchShim);
}
Expand Down
14 changes: 14 additions & 0 deletions test/regexp.js
Expand Up @@ -113,6 +113,20 @@ describe('RegExp', function () {
it('constructor does not pass through non-regexes with a truthy Symbol.match', function () {
expect(new RegExp(nonregexTruthyMatch)).not.to.equal(nonregexTruthyMatch);
});

it('is a function', function () {
expect(RegExp.prototype).to.have.property(Symbol.match);
expect(typeof RegExp.prototype[Symbol.match]).to.equal('function');
});

it('is the same as String#match', function () {
var regex = /a/g;
var str = 'abc';
var symbolMatch = regex[Symbol.match](str);
var stringMatch = str.match(regex);
expect(Object.keys(symbolMatch)).to.eql(Object.keys(stringMatch));
expect(symbolMatch).to.eql(stringMatch);
});
});
});

Expand Down
10 changes: 9 additions & 1 deletion test/string.js
Expand Up @@ -778,7 +778,15 @@ var runStringTests = function (it) {
});

describe('#match()', function () {
it('works', function () {
it('works with a string', function () {
var str = 'abca';
var match = str.match('a');
expect(match.index).to.equal(0);
expect(match.input).to.equal(str);
expect(Array.prototype.slice.call(match)).to.eql(['a']);
});

it('works with a regex', function () {
var str = 'abca';
var match = str.match(/a/);
expect(match.index).to.equal(0);
Expand Down

0 comments on commit 233ab2a

Please sign in to comment.