This repository was archived by the owner on Nov 27, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathextract_values.js
More file actions
54 lines (43 loc) · 1.39 KB
/
extract_values.js
File metadata and controls
54 lines (43 loc) · 1.39 KB
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
(function() {
var extractValues = function(str, pattern, options) {
options = options || {};
var delimiters = options.delimiters || ["{", "}"];
var lowercase = options.lowercase;
var whitespace = options.whitespace;
var special_chars_regex = /[\\\^\$\*\+\.\?\(\)]/g;
var token_regex = new RegExp( delimiters[0] + "([^" + delimiters.join("") + "\t\r\n]+)" + delimiters[1], "g");
var tokens = pattern.match(token_regex);
var pattern_regex = new RegExp(pattern.replace(special_chars_regex, "\\$&").replace(token_regex, "(\.+)"));
if (lowercase) {
str = str.toLowerCase();
}
if (whitespace) {
str = str.replace(/\s+/g, function(match) {
var whitespace_str = "";
for (var i = 0; i < whitespace; i++) {
whitespace_str = whitespace_str + match.charAt(0);
}
return whitespace_str;
});
}
var matches = str.match(pattern_regex);
if (!matches) {
return null;
}
// Allow exact string matches to return an empty object instead of null
if (!tokens) {
return (str === pattern) ? {} : null;
}
matches = matches.splice(1);
var output = {};
for (var i=0; i < tokens.length; i++) {
output[tokens[i].replace( new RegExp( delimiters[0] + "|" + delimiters[1], "g"), "").trim()] = matches[i];
}
return output;
};
if(typeof(window) !== "undefined") {
window.extractValues = extractValues;
} else {
module.exports = extractValues;
}
})();