|
1 | 1 | // 1/
|
2 |
| - |
| 2 | +// |
3 | 3 | // add sticky flag support
|
4 |
| -const original_RegExp = global.RegExp; |
| 4 | +// |
| 5 | +// src: https://github.com/paulmillr/es6-shim/issues/376#issue-118172552 |
5 | 6 |
|
6 |
| -class PolyfilledRegExp extends global.RegExp { |
7 |
| - constructor(regex, flags = '') { |
8 |
| - if (flags.indexOf("y") === -1) { |
9 |
| - return new original_RegExp(regex, flags); |
10 |
| - } |
11 |
| - super(regex, flags.replace("y", "g")); |
12 |
| - Object.defineProperty(this, "sticky", { value: true, readonly: true }); |
13 |
| - } |
| 7 | +if ( !('sticky' in global.RegExp.prototype) ) { |
| 8 | + |
| 9 | + const OriginalRegExp = global.RegExp; |
14 | 10 |
|
15 |
| - test(str) { |
16 |
| - return !!this.exec(str); |
17 |
| - } |
| 11 | + const originalExec = OriginalRegExp.prototype.exec; |
| 12 | + OriginalRegExp.prototype.exec = function (string) { |
18 | 13 |
|
19 |
| - exec(str) { |
20 | 14 | const lastIndex = this.lastIndex;
|
21 |
| - const result = super.exec(str); |
22 |
| - if (!result || result.index !== lastIndex) { |
| 15 | + const result = originalExec.call(this, string); |
| 16 | + |
| 17 | + if ( this._sticky && result != null && this.lastIndex - result[0].length !== lastIndex ) { |
| 18 | + |
23 | 19 | this.lastIndex = 0;
|
24 | 20 | return null;
|
25 | 21 | }
|
| 22 | + |
26 | 23 | return result;
|
| 24 | + }; |
| 25 | + |
| 26 | + OriginalRegExp.prototype.test = function(string) { |
| 27 | + |
| 28 | + return !!this.exec(string); |
27 | 29 | }
|
28 |
| -} |
| 30 | + |
| 31 | + function PolyfilledRegExp(pattern, flags) { |
29 | 32 |
|
30 |
| -//RegExp = PolyfilledRegExp; |
31 |
| -global.RegExp = function(regex, flags = '') { |
| 33 | + const i = flags != undefined ? flags.indexOf('y') : -1; |
| 34 | + const x = new OriginalRegExp(pattern, i === -1 ? flags : flags.slice(0, i) + flags.slice(i + 1) + (flags.indexOf('g') === -1 ? 'g' : '')); |
| 35 | + x._sticky = i !== -1; |
| 36 | + |
| 37 | + return x; |
| 38 | + }; |
32 | 39 |
|
33 |
| - return new PolyfilledRegExp(regex, flags); |
| 40 | + PolyfilledRegExp.prototype = OriginalRegExp.prototype; // handle instanceof: new RegExp('.*') instanceof RegExp |
| 41 | + |
| 42 | + global.RegExp = PolyfilledRegExp; |
34 | 43 | }
|
35 | 44 |
|
36 | 45 |
|
|
0 commit comments