Skip to content

Commit 9e8ff4b

Browse files
wip(core): enhance RegExp sticky flag support
1 parent 4e684f2 commit 9e8ff4b

File tree

1 file changed

+29
-20
lines changed

1 file changed

+29
-20
lines changed

src/bootstrap.js

Lines changed: 29 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,45 @@
11
// 1/
2-
2+
//
33
// add sticky flag support
4-
const original_RegExp = global.RegExp;
4+
//
5+
// src: https://github.com/paulmillr/es6-shim/issues/376#issue-118172552
56

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;
1410

15-
test(str) {
16-
return !!this.exec(str);
17-
}
11+
const originalExec = OriginalRegExp.prototype.exec;
12+
OriginalRegExp.prototype.exec = function (string) {
1813

19-
exec(str) {
2014
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+
2319
this.lastIndex = 0;
2420
return null;
2521
}
22+
2623
return result;
24+
};
25+
26+
OriginalRegExp.prototype.test = function(string) {
27+
28+
return !!this.exec(string);
2729
}
28-
}
30+
31+
function PolyfilledRegExp(pattern, flags) {
2932

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+
};
3239

33-
return new PolyfilledRegExp(regex, flags);
40+
PolyfilledRegExp.prototype = OriginalRegExp.prototype; // handle instanceof: new RegExp('.*') instanceof RegExp
41+
42+
global.RegExp = PolyfilledRegExp;
3443
}
3544

3645

0 commit comments

Comments
 (0)