forked from eush77/regex-format
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
71 lines (56 loc) · 1.83 KB
/
index.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
'use strict';
var oldStringFormat = String.prototype.format;
var stringFormat = require('string-format')
, escapeStringRegexp = require('escape-string-regexp')
, traverse = require('traverse')
, compose = require('lodash.compose');
// Workaround over [email protected]'s quirks.
stringFormat = (function (format) {
return function (spec) {
String.prototype.format = format;
var params = [].slice.call(arguments, 1);
if (!params.length) {
params.push(null);
}
var formatted = format.apply(spec, params);
String.prototype.format = oldStringFormat;
return formatted;
};
}(String.prototype.format));
String.prototype.format = oldStringFormat;
var regexFormat = function (spec) {
spec = RegExp(spec);
var params = [].slice.call(arguments, 1);
var source = spec.source
, flags = spec.toString().match('/([^/]*)$')[1];
// Escape substitutions.
traverse(params).forEach(function (node) {
if (this.isLeaf) {
if (typeof node == 'function') {
this.update(compose(escapeStringRegexp, String, node));
}
else {
this.update(escapeStringRegexp(String(node)));
}
}
});
// Whether a format group was matched ("{}" or "{#...}"),
// contrary to the ordinary RegExp syntax ("{1}", "{1,2}").
var group;
source = source.replace(/(\\*)(\{|\})([#}]?)/g, function (match, backslashes, brace, hash) {
if (backslashes.length % 2) {
// Escaped brace.
return backslashes + brace + brace + hash;
}
else if (brace == '{') {
group = !!hash;
return backslashes + brace + (group ? '' : brace) + (hash == '}' ? hash : '');
}
else {
return backslashes + brace + (group ? '' : brace) + hash;
}
});
source = stringFormat.apply(null, [source].concat(params));
return RegExp(source, flags);
};
module.exports = regexFormat;