forked from slevithan/xregexp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
xregexp-all.js
1957 lines (1826 loc) · 100 KB
/
xregexp-all.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***** xregexp.js *****/
/*!
* XRegExp v2.0.0-beta-3
* Copyright 2007-2012 Steven Levithan <http://xregexp.com/>
* Available under the MIT License
*/
/**
* XRegExp provides augmented, extensible JavaScript regular expressions. You get new syntax,
* flags, and methods beyond what browsers support natively. XRegExp is also a regex utility belt
* with tools to make your client-side grepping simpler and more powerful, while freeing you from
* worrying about pesky cross-browser inconsistencies and the dubious `lastIndex` property. See
* XRegExp's documentation (http://xregexp.com/) for more details.
* @module xregexp
* @requires N/A
*/
var XRegExp;
// Avoid running twice; that would duplicate tokens and could break references to native globals
XRegExp = XRegExp || (function (undef) {
"use strict";
/*--------------------------------------
* Private variables
*------------------------------------*/
var self,
addToken,
fixed,
add,
// Optional features; can be installed and uninstalled
features = {
natives: false,
methods: false,
extensibility: false
},
// Store native methods to use and restore ("native" is an ES3 reserved keyword)
nativ = {
exec: RegExp.prototype.exec,
test: RegExp.prototype.test,
match: String.prototype.match,
replace: String.prototype.replace,
split: String.prototype.split,
// Hold these so they can be given back if present before XRegExp runs
apply: RegExp.prototype.apply,
call: RegExp.prototype.call
},
// Storage for addon tokens
tokens = [],
// Token scopes
defaultScope = "default",
classScope = "class",
// Regexes that match native regex syntax
nativeTokens = {
// Any native multicharacter token in default scope (includes octals, excludes character classes)
"default": /^(?:\\(?:0(?:[0-3][0-7]{0,2}|[4-7][0-7]?)?|[1-9]\d*|x[\dA-Fa-f]{2}|u[\dA-Fa-f]{4}|c[A-Za-z]|[\s\S])|\(\?[:=!]|[?*+]\?|{\d+(?:,\d*)?}\??)/,
// Any native multicharacter token in character class scope (includes octals)
"class": /^(?:\\(?:[0-3][0-7]{0,2}|[4-7][0-7]?|x[\dA-Fa-f]{2}|u[\dA-Fa-f]{4}|c[A-Za-z]|[\s\S]))/
},
// Any backreference in replacement strings
replacementToken = /\$(?:(\d\d?|[$&`'])|{([$\w]+)})/g,
// Nonnative and duplicate flags
flagClip = /[^gimy]+|([\s\S])(?=[\s\S]*\1)/g,
// Any greedy/lazy quantifier
quantifier = /^(?:[?*+]|{\d+(?:,\d*)?})\??/,
// Check for correct `exec` handling of nonparticipating capturing groups
compliantExecNpcg = nativ.exec.call(/()??/, "")[1] === undef,
// Check for flag y support (Firefox 3+)
hasNativeY = RegExp.prototype.sticky !== undef,
// Used to kill infinite recursion during XRegExp construction
isInsideConstructor = false;
/*--------------------------------------
* Private helper functions
*------------------------------------*/
/**
* Attaches methods and special properties for named capture to a regex object.
* @private
* @param {RegExp} regex Regex to augment.
* @param {Array} captureNames Array with capture names, or null.
* @param {Boolean} [isNative] Whether the regex was created by `RegExp` rather than `XRegExp`.
* @returns {RegExp} Augmented regex.
*/
function augment(regex, captureNames, isNative) {
regex.xregexp = {captureNames: captureNames, isNative: !!isNative};
// Can't automatically inherit these since the XRegExp constructor returns a nonprimitive value
regex.apply = self.prototype.apply;
regex.call = self.prototype.call;
return regex;
}
/**
* Returns native `RegExp` flags used by a regex object.
* @private
* @param {RegExp} regex Regex to check.
* @returns {String} Native flags in use.
*/
function getNativeFlags(regex) {
//return nativ.exec.call(/\/([a-z]*)$/i, String(regex))[1];
return (regex.global ? "g" : "") +
(regex.ignoreCase ? "i" : "") +
(regex.multiline ? "m" : "") +
(regex.extended ? "x" : "") + // Proposed for ES6; included in AS3
(regex.sticky ? "y" : ""); // Firefox 3+
}
/**
* Copies a regex object while preserving special properties for named capture and augmenting with
* `XRegExp.prototype` methods. The copy has a fresh `lastIndex` property (set to zero). Allows
* adding and removing flags while copying the regex.
* @private
* @param {RegExp} regex Regex to copy.
* @param {String} [addFlags] Flags to be added while copying the regex.
* @param {String} [removeFlags] Flags to be removed while copying the regex.
* @returns {RegExp} Copy of the provided regex, possibly with modified flags.
*/
function copy(regex, addFlags, removeFlags) {
if (!self.isRegExp(regex)) {
throw new TypeError("type RegExp expected");
}
var flags = getNativeFlags(regex) + (addFlags || "");
if (removeFlags) {
// Would need to escape `removeFlags` if this was public
flags = nativ.replace.call(flags, new RegExp("[" + removeFlags + "]+", "g"), "");
}
if (regex.xregexp && !regex.xregexp.isNative) {
// Compiling the current (rather than precompilation) source preserves the effects of nonnative source flags
regex = augment(
self(regex.source, flags),
regex.xregexp.captureNames ? regex.xregexp.captureNames.slice(0) : null
);
} else {
// Remove duplicate flags to avoid throwing
flags = nativ.replace.call(flags, /([\s\S])(?=[\s\S]*\1)/g, "");
// Augment with `XRegExp.prototype` methods, but use native `RegExp` (avoid searching for special tokens)
regex = augment(new RegExp(regex.source, flags), null, true);
}
return regex;
}
/*
* Returns the first index at which a given item can be found in the array, or -1.
* @private
* @param {Array} array Array to search.
* @param {Object} item Item to locate in the array.
* @param {Number} [from=0] Zero-based index at which to begin the search.
* @returns {Number} First zero-based index at which the item was found, or -1.
*/
function indexOf(array, item, from) {
var i;
if (Array.prototype.indexOf) {
// Use the native array method if it's available
return array.indexOf(item, from);
}
for (i = from || 0; i < array.length; i++) {
if (array[i] === item) {
return i;
}
}
return -1;
}
/**
* Prepares an options object from the given value.
* @private
* @param {String|Object} value Value to convert to an options object.
* @returns {Object} Options object.
*/
function prepareOptions(value) {
value = value || {};
if (value === "all" || value.all) {
value = {natives: true, methods: true, extensibility: true};
} else if (typeof value === "string") {
value = self.forEach(value, /[^\s,]+/, function (m) {
this[m] = true;
}, {});
}
return value;
}
/**
* Runs built-in/custom tokens in order from most to least recently added, until a match is found.
* @private
* @param {String} pattern Original pattern from which an XRegExp object is being built.
* @param {Number} pos Position to search for tokens within `pattern`.
* @param {Number} scope Current regex scope.
* @param {Object} context Context object assigned to token handler functions.
* @returns {Object} Object with properties `output` (the substitution string returned by the
* successful token handler) and `match` (the token's match array), or null.
*/
function runTokens(pattern, pos, scope, context) {
var i = tokens.length,
result = null,
match,
t;
// Protect against constructing XRegExps within token handler and trigger functions
isInsideConstructor = true;
// Must reset `isInsideConstructor`, even if a `trigger` or `handler` throws
try {
while (i--) { // Run in reverse order
t = tokens[i];
if ((t.scope === "all" || t.scope === scope) && (!t.trigger || t.trigger.call(context))) {
t.pattern.lastIndex = pos;
match = fixed.exec.call(t.pattern, pattern); // Fixed `exec` here allows use of named backreferences, etc.
if (match && match.index === pos) {
result = {
output: t.handler.call(context, match, scope),
match: match
};
break;
}
}
}
} catch (err) {
throw err;
} finally {
isInsideConstructor = false;
}
return result;
}
/**
* Enables or disables XRegExp syntax and flag extensibility.
* @private
* @param {Boolean} on `true` to enable; `false` to disable.
* @returns {undefined} N/A
*/
function setExtensibility(on) {
self.addToken = addToken[on ? "on" : "off"];
features.extensibility = on;
}
/**
* Enables or disables new `RegExp.prototype` methods.
* @private
* @param {Boolean} on `true` to enable; `false` to disable.
* @returns {undefined} N/A
*/
function setMethods(on) {
if (on) {
RegExp.prototype.apply = self.prototype.apply;
RegExp.prototype.call = self.prototype.call;
} else {
// Restore methods if they existed before XRegExp ran; otherwise delete
if (nativ.apply) {
RegExp.prototype.apply = nativ.apply;
} else {
delete RegExp.prototype.apply;
}
if (nativ.call) {
RegExp.prototype.call = nativ.call;
} else {
delete RegExp.prototype.call;
}
}
features.methods = on;
}
/**
* Enables or disables native method overrides.
* @private
* @param {Boolean} on `true` to enable; `false` to disable.
* @returns {undefined} N/A
*/
function setNatives(on) {
RegExp.prototype.exec = (on ? fixed : nativ).exec;
RegExp.prototype.test = (on ? fixed : nativ).test;
String.prototype.match = (on ? fixed : nativ).match;
String.prototype.replace = (on ? fixed : nativ).replace;
String.prototype.split = (on ? fixed : nativ).split;
features.natives = on;
}
/*--------------------------------------
* Constructor
*------------------------------------*/
/**
* Creates an extended regular expression object for matching text with a pattern. Differs from a
* native regular expression in that additional syntax and flags are supported. The returned object
* is in fact a native `RegExp` and works with all native methods.
* @class XRegExp
* @constructor
* @param {String} pattern Regular expression pattern string.
* @param {String} [flags] Any combination of flags:
* <li>`g` - global
* <li>`i` - ignore case
* <li>`m` - multiline anchors
* <li>`n` - explicit capture
* <li>`s` - dot matches all (aka singleline)
* <li>`x` - free-spacing and line comments (aka extended)
* <li>`y` - sticky (Firefox 3+ only)
* @returns {RegExp} Extended regular expression object.
* @example
*
* // With named capture and flag x
* date = XRegExp('(?<year> [0-9]{4}) -? # year \n\
* (?<month> [0-9]{2}) -? # month \n\
* (?<day> [0-9]{2}) # day ', 'x');
*
* // Special case: Pass a regex object to copy it. The copy maintains special properties for named
* // capture, is augmented with `XRegExp.prototype` methods, and has a fresh `lastIndex` property
* // (set to zero). Native regexes are not recompiled using XRegExp syntax.
* XRegExp(/regex/);
*/
self = function (pattern, flags) {
if (self.isRegExp(pattern)) {
if (flags !== undef) {
throw new TypeError("can't supply flags when constructing one RegExp from another");
}
return copy(pattern);
}
// Tokens become part of the regex construction process, so protect against infinite recursion
// when an XRegExp is constructed within a token handler function
if (isInsideConstructor) {
throw new Error("can't call the XRegExp constructor within token definition functions");
}
var output = [],
scope = defaultScope,
tokenContext = {
hasNamedCapture: false,
captureNames: [],
hasFlag: function (flag) {
return flags.indexOf(flag) > -1;
},
setFlag: function (flag) {
flags += flag;
}
},
pos = 0,
tokenResult,
match,
chr;
pattern = pattern === undef ? "" : String(pattern);
flags = flags === undef ? "" : String(flags);
while (pos < pattern.length) {
// Check for custom tokens at the current position
tokenResult = runTokens(pattern, pos, scope, tokenContext);
if (tokenResult) {
output.push(tokenResult.output);
pos += (tokenResult.match[0].length || 1);
} else {
// Check for native tokens (except character classes) at the current position
match = nativ.exec.call(nativeTokens[scope], pattern.slice(pos));
if (match) {
output.push(match[0]);
pos += match[0].length;
} else {
chr = pattern.charAt(pos);
if (chr === "[") {
scope = classScope;
} else if (chr === "]") {
scope = defaultScope;
}
// Advance position by one character
output.push(chr);
pos++;
}
}
}
return augment(
new RegExp(output.join(""), nativ.replace.call(flags, flagClip, "")),
tokenContext.hasNamedCapture ? tokenContext.captureNames : null
);
};
/*--------------------------------------
* Public methods/properties
*------------------------------------*/
// Installed and uninstalled states for `XRegExp.addToken`
addToken = {
on: function (regex, handler, options) {
options = options || {};
tokens.push({
pattern: copy(regex, "g" + (hasNativeY ? "y" : "")),
handler: handler,
scope: options.scope || defaultScope,
trigger: options.trigger || null
});
},
off: function () {
throw new Error("extensibility must be installed before running addToken");
}
};
/**
* Extends or changes XRegExp syntax and allows custom flags. This is used internally by XRegExp
* and can be used to create XRegExp addons. `XRegExp.install('extensibility')` must be run before
* calling this function, or an error is thrown. If more than one token can match the same string,
* the last added wins.
* @memberOf XRegExp
* @param {RegExp} regex Regex object that matches the new token.
* @param {Function} handler Function that returns a new pattern string (using native regex syntax)
* to replace the matched token within all future XRegExp regexes. Has access to persistent
* properties of the regex being built, through `this`. Invoked with two arguments:
* <li>The match array, with named backreference properties.
* <li>The regex scope where the match was found.
* @param {Object} [options] Options object with optional properties:
* <li>`scope` {String} Scopes where the token applies: 'default', 'class', or 'all'.
* <li>`trigger` {Function} Function that returns `true` when the token should be applied; e.g.,
* if a flag is set. If `false` is returned, the matched string can be matched by other tokens.
* Has access to persistent properties of the regex being built, through `this` (including
* function `this.hasFlag`).
* @returns {undefined} N/A
* @example
*
* // Adds support for escape sequences: \Q..\E and \Q..
* XRegExp.addToken(
* /\\Q([\s\S]*?)(?:\\E|$)/,
* function (match) {return XRegExp.escape(match[1]);},
* {scope: 'all'}
* );
*/
self.addToken = addToken.off;
/**
* Caches and returns the result of calling `XRegExp(pattern, flags)`. On any subsequent call with
* the same pattern and flag combination, the cached copy is returned.
* @memberOf XRegExp
* @param {String} pattern Regular expression pattern string.
* @param {String} [flags] Any combination of flags.
* @returns {RegExp} Cached XRegExp object.
* @example
*
* while (match = XRegExp.cache('.', 'gs').exec(str)) {
* // The regex is compiled once only
* }
*/
self.cache = function (pattern, flags) {
var key = pattern + "/" + (flags || "");
return self.cache[key] || (self.cache[key] = self(pattern, flags));
};
/**
* Escapes any regular expression metacharacters, for use when matching literal strings. The result
* can safely be used at any point within a regex that uses any flags.
* @memberOf XRegExp
* @param {String} str String to escape.
* @returns {String} String with regex metacharacters escaped.
* @example
*
* XRegExp.escape('Escaped? <.>');
* // -> 'Escaped\?\ <\.>'
*/
self.escape = function (str) {
return nativ.replace.call(str, /[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
};
/**
* Executes a regex search in a specified string. Returns a match array or `null`. If the provided
* regex uses named capture, named backreference properties are included on the match array.
* Optional `pos` and `sticky` arguments specify the search start position, and whether the match
* must start at the specified position only. The `lastIndex` property of the provided regex is not
* used, but is updated for compatibility. Also fixes browser bugs compared to the native
* `RegExp.prototype.exec` and can be used reliably cross-browser.
* @memberOf XRegExp
* @param {String} str String to search.
* @param {RegExp} regex Regular expression to search with.
* @param {Number} [pos=0] Zero-based index at which to start the search.
* @param {Boolean|String} [sticky=false] Whether the match must start at the specified position
* only. The string `'sticky'` is accepted as an alternative to `true`.
* @returns {Array} Match array with named backreference properties, or null.
* @example
*
* // Basic use, with named backreference
* var match = XRegExp.exec('U+2620', XRegExp('U\\+(?<hex>[0-9A-F]{4})'));
* match.hex; // -> '2620'
*
* // With pos and sticky, in a loop
* var pos = 2, result = [], match;
* while (match = XRegExp.exec('<1><2><3><4>5<6>', /<(\d)>/, pos, 'sticky')) {
* result.push(match[1]);
* pos = match.index + match[0].length;
* }
* // result -> ['2', '3', '4']
*/
self.exec = function (str, regex, pos, sticky) {
var r2 = copy(regex, "g" + ((sticky && hasNativeY) ? "y" : "")),
match;
r2.lastIndex = pos = pos || 0;
match = fixed.exec.call(r2, str); // Fixed `exec` required for `lastIndex` fix, etc.
if (sticky && match && match.index !== pos) {
match = null;
}
if (regex.global) {
regex.lastIndex = match ? r2.lastIndex : 0;
}
return match;
};
/**
* Executes a provided function once per regex match.
* @memberOf XRegExp
* @param {String} str String to search.
* @param {RegExp} regex Regular expression to search with.
* @param {Function} callback Function to execute for each match. Invoked with four arguments:
* <li>The match array, with named backreference properties.
* <li>The zero-based match index.
* <li>The string being traversed.
* <li>The regex object being used to traverse the string.
* @param {*} [context] Object to use as `this` when executing `callback`.
* @returns {*} Provided `context` object.
* @example
*
* // Extracts every other digit from a string
* XRegExp.forEach("1a2345", /\d/, function (match, i) {
* if (i % 2) this.push(+match[0]);
* }, []);
* // -> [2, 4]
*/
self.forEach = function (str, regex, callback, context) {
var r2 = self.globalize(regex),
i = -1,
match;
while ((match = fixed.exec.call(r2, str))) { // Fixed `exec` required for `lastIndex` fix, etc.
if (regex.global) {
// Doing this to follow expectations if `lastIndex` is checked within `callback`
regex.lastIndex = r2.lastIndex;
}
callback.call(context, match, ++i, str, regex);
if (r2.lastIndex === match.index) {
r2.lastIndex++;
}
}
if (regex.global) {
regex.lastIndex = 0;
}
return context;
};
/**
* Copies a regex object and adds flag g. The copy maintains special properties for named capture,
* is augmented with `XRegExp.prototype` methods, and has a fresh `lastIndex` property (set to
* zero). Native regexes are not recompiled using XRegExp syntax.
* @memberOf XRegExp
* @param {RegExp} regex Regex to globalize.
* @returns {RegExp} Copy of the provided regex with flag g added.
* @example
*
* var globalCopy = XRegExp.globalize(/regex/);
* globalCopy.global; // -> true
*/
self.globalize = function (regex) {
return copy(regex, "g");
};
/**
* Installs optional features according to the specified options.
* @memberOf XRegExp
* @param {Object|String} options Options object or string.
* @returns {undefined} N/A
* @example
*
* // With an options object
* XRegExp.install({
* // Overrides native regex methods with fixed/extended versions that support named
* // backreferences and fix numerous cross-browser bugs
* natives: true,
*
* // Copies XRegExp.prototype methods to RegExp.prototype
* methods: true,
*
* // Enables extensibility of XRegExp syntax and flag (used by addons)
* extensibility: true
* });
*
* // With an options string
* XRegExp.install('natives methods');
*
* // Using a shortcut to install all optional features
* XRegExp.install('all');
*/
self.install = function (options) {
options = prepareOptions(options);
if (!features.natives && options.natives) {
setNatives(true);
}
if (!features.methods && options.methods) {
setMethods(true);
}
if (!features.extensibility && options.extensibility) {
setExtensibility(true);
}
};
/**
* Returns `true` if an object is a regex; `false` if it isn't. This works correctly for regexes
* created in another frame, when `instanceof` and `constructor` checks would fail.
* @memberOf XRegExp
* @param {*} value Object to check.
* @returns {Boolean} Whether the object is a `RegExp` object.
* @example
*
* XRegExp.isRegExp(XRegExp('(?s).')); // -> true
*/
self.isRegExp = function (value) {
return Object.prototype.toString.call(value) === "[object RegExp]";
};
/**
* Checks whether an individual optional feature is installed.
* @memberOf XRegExp
* @param {String} feature Name of the feature to check. Any one of:
* <li>`natives`
* <li>`methods`
* <li>`extensibility`
* @returns {Boolean} Whether the feature is installed.
* @example
*
* XRegExp.isInstalled('natives');
*/
self.isInstalled = function (feature) {
return !!(features[feature]);
};
/**
* Retrieves the matches from searching a string using a chain of regexes that successively search
* within previous matches. The provided `chain` array can contain regexes and objects with `regex`
* and `backref` properties. When a backreference is specified, the named or numbered backreference
* is passed forward to the next regex or returned.
* @memberOf XRegExp
* @param {String} str String to search.
* @param {Array} chain Regexes that each search for matches within preceding results.
* @returns {Array} Matches by the last regex in the chain, or an empty array.
* @example
*
* // Basic usage; matches numbers within <b> tags
* XRegExp.matchChain('1 <b>2</b> 3 <b>4 a 56</b>', [
* XRegExp('(?is)<b>.*?<\\/b>'),
* /\d+/
* ]);
* // -> ['2', '4', '56']
*
* // Passing forward and returning specific backreferences
* XRegExp.matchChain(html, [
* {regex: /<a href="([^"]+)">/i, backref: 1},
* {regex: XRegExp('(?i)^https?://(?<domain>[^/?#]+)'), backref: 'domain'}
* ]);
*/
self.matchChain = function (str, chain) {
return (function recurseChain(values, level) {
var item = chain[level].regex ? chain[level] : {regex: chain[level]},
regex = self.globalize(item.regex),
matches = [],
fn = function (match) {
matches.push(item.backref ? (match[item.backref] || "") : match[0]);
},
i;
for (i = 0; i < values.length; i++) {
self.forEach(values[i], regex, fn);
}
return ((level === chain.length - 1) || !matches.length) ?
matches :
recurseChain(matches, level + 1);
}([str], 0));
};
/**
* Returns a new string with one or all matches of a pattern replaced. The pattern can be a string
* or regex, and the replacement can be a string or a function to be called for each match. To
* perform a global search and replace, use the optional `scope` argument or include flag g if
* using a regex. Replacement strings can use `${n}` for named and numbered backreferences.
* Replacement functions can use named backreferences via `arguments[0].name`. Also fixes browser
* bugs compared to the native `String.prototype.replace` and can be used reliably cross-browser.
* @memberOf XRegExp
* @param {String} str String to search.
* @param {RegExp|String} search Search pattern to be replaced.
* @param {String|Function} replacement Replacement string or a function invoked to create it.
* Replacement strings can include special replacement patterns:
* <li>$$ - Inserts a "$".
* <li>$& - Inserts the matched substring.
* <li>$` - Inserts the string portion that precedes the matched substring.
* <li>$' - Inserts the string portion that follows the matched substring.
* <li>$n/$nn - Where n/nn are digits referencing an existent capturing group, inserts
* backreference n/nn.
* <li>${n} - Where n is a name or any number of digits that reference an existent capturing
* group, inserts backreference n.
* Replacement functions are invoked with three or more arguments:
* <li>The matched substring (corresponds to $& above). Named backreferences are accessible as
* properties of this first argument.
* <li>0..n arguments, one for each backreference (corresponding to $1, $2, etc. above).
* <li>The zero-based index of the match within the total search string.
* <li>The total string being searched.
* @param {String} [scope='one'] Use 'one' to replace the first match only, or 'all'. If not
* explicitly specified and using a regex with flag g, `scope` is 'all'.
* @returns {String} New string with one or all matches replaced.
* @example
*
* // Regex search, using named backreferences in replacement string
* var name = XRegExp('(?<first>\\w+) (?<last>\\w+)');
* XRegExp.replace('John Smith', name, '${last}, ${first}');
* // -> 'Smith, John'
*
* // Regex search, using named backreferences in replacement function
* XRegExp.replace('John Smith', name, function (match) {
* return match.last + ', ' + match.first;
* });
* // -> 'Smith, John'
*
* // Global string search/replacement
* XRegExp.replace('RegExp builds RegExps', 'RegExp', 'XRegExp', 'all');
* // -> 'XRegExp builds XRegExps'
*/
self.replace = function (str, search, replacement, scope) {
var isRegex = self.isRegExp(search),
search2 = search,
result;
if (isRegex) {
if (scope === undef && search.global) {
scope = "all"; // Follow flag g when `scope` isn't explicit
}
// Note that since a copy is used, `search`'s `lastIndex` isn't updated *during* replacement iterations
search2 = copy(search, scope === "all" ? "g" : "", scope === "all" ? "" : "g");
} else if (scope === "all") {
search2 = new RegExp(self.escape(String(search)), "g");
}
result = fixed.replace.call(String(str), search2, replacement); // Fixed `replace` required for named backreferences, etc.
if (isRegex && search.global) {
search.lastIndex = 0; // Fixes IE, Safari bug (last tested IE 9, Safari 5.1)
}
return result;
};
/**
* Splits a string into an array of strings using a regex or string separator. Matches of the
* separator are not included in the result array. However, if `separator` is a regex that contains
* capturing groups, backreferences are spliced into the result each time `separator` is matched.
* Fixes browser bugs compared to the native `String.prototype.split` and can be used reliably
* cross-browser.
* @memberOf XRegExp
* @param {String} str String to split.
* @param {RegExp|String} separator Regex or string to use for separating the string.
* @param {Number} [limit] Maximum number of items to include in the result array.
* @returns {Array} Array of substrings.
* @example
*
* // Basic use
* XRegExp.split('a b c d', ' ');
* // -> ['a', 'b', 'c', 'd']
*
* // With limit
* XRegExp.split('a b c d', ' ', 2);
* // -> ['a', 'b']
*
* // Backreferences in result array
* XRegExp.split('..word1 word2..', /([a-z]+)(\d+)/i);
* // -> ['..', 'word', '1', ' ', 'word', '2', '..']
*/
self.split = function (str, separator, limit) {
return fixed.split.call(str, separator, limit);
};
/**
* Uninstalls optional features according to the specified options.
* @memberOf XRegExp
* @param {Object|String} options Options object or string.
* @returns {undefined} N/A
* @example
*
* // With an options object
* XRegExp.uninstall({
* // Restores native regex methods
* natives: true,
*
* // Removes added RegExp.prototype methods, or restores their original values
* methods: true,
*
* // Disables additional syntax and flag extensions
* extensibility: true
* });
*
* // With an options string
* XRegExp.uninstall('natives methods');
*
* // Using a shortcut to uninstall all optional features
* XRegExp.uninstall('all');
*/
self.uninstall = function (options) {
options = prepareOptions(options);
if (features.natives && options.natives) {
setNatives(false);
}
if (features.methods && options.methods) {
setMethods(false);
}
if (features.extensibility && options.extensibility) {
setExtensibility(false);
}
};
/**
* The semantic version number.
* @static
* @memberOf XRegExp
* @type String
*/
self.version = "2.0.0-beta-3";
/*--------------------------------------
* XRegExp.prototype methods
*------------------------------------*/
/**
* Calls an XRegExp object's `test` method with the first value in the provided arguments array.
* @memberOf XRegExp.prototype
* @param {*} context Ignored. Accepted only for congruity with `Function.prototype.apply`.
* @param {Array} args Array with the string to search as its first value.
* @returns {Boolean} Whether the regex matched the provided value.
* @example
*
* XRegExp('.').apply(null, ['abc']); // -> true
*
* // Regexes copied by XRegExp also get the apply method
* XRegExp(/./).apply(null, ['abc']); // -> true
*/
self.prototype.apply = function (context, args) {
return this.test(args[0]); // Intentionally doesn't specify fixed/native `test`
};
/**
* Calls an XRegExp object's `test` method with the provided string.
* @memberOf XRegExp.prototype
* @param {*} context Ignored. Accepted only for congruity with `Function.prototype.call`.
* @param {String} str String to search.
* @returns {Boolean} Whether the regex matched the provided value.
* @example
*
* XRegExp('.').call(null, 'abc'); // -> true
*
* // Regexes copied by XRegExp also get the call method
* XRegExp(/./).call(null, 'abc'); // -> true
*/
self.prototype.call = function (context, str) {
return this.test(str); // Intentionally doesn't specify fixed/native `test`
};
/*--------------------------------------
* Fixed/extended native methods
*------------------------------------*/
fixed = {};
/**
* Adds named capture support (with backreferences returned as `result.name`), and fixes browser
* bugs in the native `RegExp.prototype.exec`. Calling `XRegExp.install('natives')` uses this to
* override the native method. Use via `XRegExp.exec` without overriding natives.
* @private
* @param {String} str String to search.
* @returns {Array} Match array with named backreference properties, or null.
*/
fixed.exec = function (str) {
var match, name, r2, origLastIndex, i;
if (!this.global) {
origLastIndex = this.lastIndex;
}
match = nativ.exec.apply(this, arguments);
if (match) {
// Fix browsers whose `exec` methods don't consistently return `undefined` for
// nonparticipating capturing groups
if (!compliantExecNpcg && match.length > 1 && indexOf(match, "") > -1) {
r2 = new RegExp(this.source, nativ.replace.call(getNativeFlags(this), "g", ""));
// Using `str.slice(match.index)` rather than `match[0]` in case lookahead allowed
// matching due to characters outside the match
nativ.replace.call(String(str).slice(match.index), r2, function () {
var i;
for (i = 1; i < arguments.length - 2; i++) {
if (arguments[i] === undef) {
match[i] = undef;
}
}
});
}
// Attach named capture properties
if (this.xregexp && this.xregexp.captureNames) {
for (i = 1; i < match.length; i++) {
name = this.xregexp.captureNames[i - 1];
if (name) {
match[name] = match[i];
}
}
}
// Fix browsers that increment `lastIndex` after zero-length matches
if (this.global && !match[0].length && (this.lastIndex > match.index)) {
this.lastIndex = match.index;
}
}
if (!this.global) {
this.lastIndex = origLastIndex; // Fixes IE, Opera bug (last tested IE 9, Opera 11.6)
}
return match;
};
/**
* Fixes browser bugs in the native `RegExp.prototype.test`. Calling `XRegExp.install('natives')`
* uses this to override the native method.
* @private
* @param {String} str String to search.
* @returns {Boolean} Whether the regex matched the provided value.
*/
fixed.test = function (str) {
// Do this the easy way :-)
return !!fixed.exec.call(this, str);
};
/**
* Adds named capture support (with backreferences returned as `result.name`), and fixes browser
* bugs in the native `String.prototype.match`. Calling `XRegExp.install('natives')` uses this to
* override the native method.
* @private
* @param {RegExp} regex Regular expression to search with.
* @returns {Array} If `regex` uses flag g, an array of match strings or null. Without flag g, the
* result of calling `regex.exec(this)`.
*/
fixed.match = function (regex) {
if (!self.isRegExp(regex)) {
regex = new RegExp(regex); // Use native `RegExp`
} else if (regex.global) {
var result = nativ.match.apply(this, arguments);
regex.lastIndex = 0; // Fixes IE bug
return result;
}
return fixed.exec.call(regex, this);
};
/**
* Adds support for `${n}` tokens for named and numbered backreferences in replacement text, and
* provides named backreferences to replacement functions as `arguments[0].name`. Also fixes
* browser bugs in replacement text syntax when performing a replacement using a nonregex search
* value, and the value of a replacement regex's `lastIndex` property during replacement iterations
* and upon completion. Note that this doesn't support SpiderMonkey's proprietary third (`flags`)
* argument. Calling `XRegExp.install('natives')` uses this to override the native method. Use via
* `XRegExp.replace` without overriding natives.
* @private
* @param {RegExp|String} search Search pattern to be replaced.
* @param {String|Function} replacement Replacement string or a function invoked to create it.
* @returns {String} New string with one or all matches replaced.
*/
fixed.replace = function (search, replacement) {
var isRegex = self.isRegExp(search), captureNames, result, str, origLastIndex;
if (isRegex) {
if (search.xregexp) {
captureNames = search.xregexp.captureNames;
}
if (!search.global) {
origLastIndex = search.lastIndex;
}
} else {
search += "";
}
if (Object.prototype.toString.call(replacement) === "[object Function]") {
result = nativ.replace.call(String(this), search, function () {
var args = arguments, i;
if (captureNames) {
// Change the `arguments[0]` string primitive to a `String` object that can store properties
args[0] = new String(args[0]);
// Store named backreferences on the first argument
for (i = 0; i < captureNames.length; i++) {
if (captureNames[i]) {
args[0][captureNames[i]] = args[i + 1];
}
}
}
// Update `lastIndex` before calling `replacement`.
// Fixes IE, Chrome, Firefox, Safari bug (last tested IE 9, Chrome 17, Firefox 10, Safari 5.1)
if (isRegex && search.global) {
search.lastIndex = args[args.length - 2] + args[0].length;
}
return replacement.apply(null, args);
});
} else {
str = String(this); // Ensure `args[args.length - 1]` will be a string when given nonstring `this`
result = nativ.replace.call(str, search, function () {
var args = arguments; // Keep this function's `arguments` available through closure
return nativ.replace.call(String(replacement), replacementToken, function ($0, $1, $2) {
var literalNumbers, n;
// Numbered backreference (without delimiters) or special variable
if ($1) {
if ($1 === "$") {
return "$";
}
if ($1 === "&") {
return args[0];
}
if ($1 === "`") {
return args[args.length - 1].slice(0, args[args.length - 2]);