UNPKG

1.66 kBJavaScriptView Raw
1'use strict';
2var regexpFlags = require('./regexp-flags');
3
4var nativeExec = RegExp.prototype.exec;
5// This always refers to the native implementation, because the
6// String#replace polyfill uses ./fix-regexp-well-known-symbol-logic.js,
7// which loads this file before patching the method.
8var nativeReplace = String.prototype.replace;
9
10var patchedExec = nativeExec;
11
12var UPDATES_LAST_INDEX_WRONG = (function () {
13 var re1 = /a/;
14 var re2 = /b*/g;
15 nativeExec.call(re1, 'a');
16 nativeExec.call(re2, 'a');
17 return re1.lastIndex !== 0 || re2.lastIndex !== 0;
18})();
19
20// nonparticipating capturing group, copied from es5-shim's String#split patch.
21var NPCG_INCLUDED = /()??/.exec('')[1] !== undefined;
22
23var PATCH = UPDATES_LAST_INDEX_WRONG || NPCG_INCLUDED;
24
25if (PATCH) {
26 patchedExec = function exec(str) {
27 var re = this;
28 var lastIndex, reCopy, match, i;
29
30 if (NPCG_INCLUDED) {
31 reCopy = new RegExp('^' + re.source + '$(?!\\s)', regexpFlags.call(re));
32 }
33 if (UPDATES_LAST_INDEX_WRONG) lastIndex = re.lastIndex;
34
35 match = nativeExec.call(re, str);
36
37 if (UPDATES_LAST_INDEX_WRONG && match) {
38 re.lastIndex = re.global ? match.index + match[0].length : lastIndex;
39 }
40 if (NPCG_INCLUDED && match && match.length > 1) {
41 // Fix browsers whose `exec` methods don't consistently return `undefined`
42 // for NPCG, like IE8. NOTE: This doesn' work for /(.?)?/
43 nativeReplace.call(match[0], reCopy, function () {
44 for (i = 1; i < arguments.length - 2; i++) {
45 if (arguments[i] === undefined) match[i] = undefined;
46 }
47 });
48 }
49
50 return match;
51 };
52}
53
54module.exports = patchedExec;