-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathjquery.format.js
120 lines (93 loc) · 2.6 KB
/
jquery.format.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
/**
* jQuery string format plugin
* http://github.com/krzyzak00/format
*
* Copright (c) 2011 Przemysław Kościelniak
* Dual licensed under the MIT and GPL
*
* Adds Python-like format function to jQuery
* This is basic implementation and it doesn't cover all Python format features
* @param {string} string
* @param {mixed} variables
* @return {string} formated string
*/
/*
Usage examples:
$.fn.format('The quick {} {} jumped over the {} {}', "brown", "fox", "lazy", "dog");
$.fn.format('The quick {0} {2} jumped over the {1} {3}', "brown", "lazy", "fox", "dog");
$.fn.format('The quick {_brown_} {_fox_} jumped over the {_lazy_} {_dog_}', {
_brown_: "brown",
_fox_: "Fox",
_lazy_: "lazy",
_dog_: "Dog"
});
$.fn.format('The quick {0} {1} jumped over the {2} {3}', {
0: "brown",
1: "fox",
2: "lazy",
3: "dog"
});
*/
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else {
// Browser globals
factory(jQuery);
}
}(function ($) {
$.fn.format = function() {
var isArguments = function(obj) {
return obj.constructor !== String && obj.constructor !== Array && obj.length;
};
var args = isArguments(arguments[0]) ? arguments[0] : arguments,
alen = args.length;
// no arguments given
if (!alen) { return null; }
// if only one argument given assume it's string and simply return it
else if (alen === 1) { return args[0]; }
// second argument is either variable or object with named vars
else {
var str = args[0],
matches = str.match(/{[^}]*}/g),
mlen = matches ? matches.length : 0,
i = 0,
name, val, r;
// for object with named variables
if (typeof(args[1]) === 'object') {
while (i < mlen) {
name = matches[i].replace(/{/, '').replace(/}/, '');
val = args[1][name];
var rs = '';
if (isNaN(parseInt(name, 10))) {
rs = "{" + name + "}";
} else {
rs = "{[" + i + "]}";
}
r = new RegExp(rs, "g");
str = str.replace(r, args[1][name]);
i++;
}
return str;
} else { // for variables as arguments
if (!matches || matches.length !== alen - 1) {
throw "Format: wrong number of arguments, " + str;
}
while (i < alen - 1) {
// replace {} {} {} ... {}
if (matches[i].length === 2) {
str = str.replace('{}', args[i + 1]);
}
// replace {0} {1} {2} ... {n}
else {
r = new RegExp("{[" + i + "]}", "g");
str = str.replace(r, args[i + 1]);
}
i++;
}
return str;
}
}
};
}));