6cd4da790be547fb46f4cedf7e989cc337e77cac.svn-base
15.6 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
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
// Underscore.string
// (c) 2010 Esa-Matti Suuronen <esa-matti aet suuronen dot org>
// Underscore.strings is freely distributable under the terms of the MIT license.
// Documentation: https://github.com/epeli/underscore.string
// Some code is borrowed from MooTools and Alexandru Marasteanu.
// Version 2.1.1
(function(root){
'use strict';
// Defining helper functions.
var nativeTrim = String.prototype.trim;
var nativeTrimRight = String.prototype.trimRight;
var nativeTrimLeft = String.prototype.trimLeft;
var parseNumber = function(source) { return source * 1 || 0; };
var strRepeat = function(str, qty, separator){
// ~~var — is the fastest available way to convert anything to Integer in javascript.
// We'll use it extensively in this lib.
str += ''; qty = ~~qty;
for (var repeat = []; qty > 0; repeat[--qty] = str) {}
return repeat.join(separator == null ? '' : separator);
};
var slice = function(a){
return Array.prototype.slice.call(a);
};
var defaultToWhiteSpace = function(characters){
if (characters != null) {
return '[' + _s.escapeRegExp(''+characters) + ']';
}
return '\\s';
};
// sprintf() for JavaScript 0.7-beta1
// http://www.diveintojavascript.com/projects/javascript-sprintf
//
// Copyright (c) Alexandru Marasteanu <alexaholic [at) gmail (dot] com>
// All rights reserved.
var sprintf = (function() {
function get_type(variable) {
return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
}
var str_repeat = strRepeat;
var str_format = function() {
if (!str_format.cache.hasOwnProperty(arguments[0])) {
str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
}
return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
};
str_format.format = function(parse_tree, argv) {
var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
for (i = 0; i < tree_length; i++) {
node_type = get_type(parse_tree[i]);
if (node_type === 'string') {
output.push(parse_tree[i]);
}
else if (node_type === 'array') {
match = parse_tree[i]; // convenience purposes only
if (match[2]) { // keyword argument
arg = argv[cursor];
for (k = 0; k < match[2].length; k++) {
if (!arg.hasOwnProperty(match[2][k])) {
throw new Error(sprintf('[_.sprintf] property "%s" does not exist', match[2][k]));
}
arg = arg[match[2][k]];
}
} else if (match[1]) { // positional argument (explicit)
arg = argv[match[1]];
}
else { // positional argument (implicit)
arg = argv[cursor++];
}
if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
throw new Error(sprintf('[_.sprintf] expecting number but found %s', get_type(arg)));
}
switch (match[8]) {
case 'b': arg = arg.toString(2); break;
case 'c': arg = String.fromCharCode(arg); break;
case 'd': arg = parseInt(arg, 10); break;
case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
case 'o': arg = arg.toString(8); break;
case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
case 'u': arg = Math.abs(arg); break;
case 'x': arg = arg.toString(16); break;
case 'X': arg = arg.toString(16).toUpperCase(); break;
}
arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
pad_length = match[6] - String(arg).length;
pad = match[6] ? str_repeat(pad_character, pad_length) : '';
output.push(match[5] ? arg + pad : pad + arg);
}
}
return output.join('');
};
str_format.cache = {};
str_format.parse = function(fmt) {
var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
while (_fmt) {
if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
parse_tree.push(match[0]);
}
else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
parse_tree.push('%');
}
else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
if (match[2]) {
arg_names |= 1;
var field_list = [], replacement_field = match[2], field_match = [];
if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
field_list.push(field_match[1]);
while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
field_list.push(field_match[1]);
}
else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
field_list.push(field_match[1]);
}
else {
throw new Error('[_.sprintf] huh?');
}
}
}
else {
throw new Error('[_.sprintf] huh?');
}
match[2] = field_list;
}
else {
arg_names |= 2;
}
if (arg_names === 3) {
throw new Error('[_.sprintf] mixing positional and named placeholders is not (yet) supported');
}
parse_tree.push(match);
}
else {
throw new Error('[_.sprintf] huh?');
}
_fmt = _fmt.substring(match[0].length);
}
return parse_tree;
};
return str_format;
})();
// Defining underscore.string
var _s = {
VERSION: '2.1.1',
isBlank: function(str){
return (/^\s*$/).test(str);
},
stripTags: function(str){
return (''+str).replace(/<\/?[^>]+>/ig, '');
},
capitalize : function(str) {
str += '';
return str.charAt(0).toUpperCase() + str.substring(1).toLowerCase();
},
chop: function(str, step){
str = str+'';
step = ~~step || str.length;
var arr = [];
for (var i = 0; i < str.length;) {
arr.push(str.slice(i,i + step));
i = i + step;
}
return arr;
},
clean: function(str){
return _s.strip((''+str).replace(/\s+/g, ' '));
},
count: function(str, substr){
str += ''; substr += '';
return str.split(substr).length - 1;
},
chars: function(str) {
return (''+str).split('');
},
escapeHTML: function(str) {
return (''+str).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>')
.replace(/"/g, '"').replace(/'/g, "'");
},
unescapeHTML: function(str) {
return (''+str).replace(/</g, '<').replace(/>/g, '>')
.replace(/"/g, '"').replace(/'/g, "'").replace(/&/g, '&');
},
escapeRegExp: function(str){
// From MooTools core 1.2.4
return str.replace(/([-.*+?^${}()|[\]\/\\])/g, '\\$1');
},
insert: function(str, i, substr){
var arr = (''+str).split('');
arr.splice(~~i, 0, ''+substr);
return arr.join('');
},
include: function(str, needle){
return (''+str).indexOf(needle) !== -1;
},
join: function(sep) {
var args = slice(arguments);
return args.join(args.shift());
},
lines: function(str) {
return (''+str).split("\n");
},
reverse: function(str){
return Array.prototype.reverse.apply(String(str).split('')).join('');
},
splice: function(str, i, howmany, substr){
var arr = (''+str).split('');
arr.splice(~~i, ~~howmany, substr);
return arr.join('');
},
startsWith: function(str, starts){
str += ''; starts += '';
return str.length >= starts.length && str.substring(0, starts.length) === starts;
},
endsWith: function(str, ends){
str += ''; ends += '';
return str.length >= ends.length && str.substring(str.length - ends.length) === ends;
},
succ: function(str){
str += '';
var arr = str.split('');
arr.splice(str.length-1, 1, String.fromCharCode(str.charCodeAt(str.length-1) + 1));
return arr.join('');
},
titleize: function(str){
return (''+str).replace(/\b./g, function(ch){ return ch.toUpperCase(); });
},
camelize: function(str){
return _s.trim(str).replace(/(\-|_|\s)+(.)?/g, function(match, separator, chr) {
return chr ? chr.toUpperCase() : '';
});
},
underscored: function(str){
return _s.trim(str).replace(/([a-z\d])([A-Z]+)/g, '$1_$2').replace(/[-\s]+/g, '_').toLowerCase();
},
dasherize: function(str){
return _s.trim(str).replace(/[_\s]+/g, '-').replace(/([A-Z])/g, '-$1').replace(/-+/g, '-').toLowerCase();
},
classify: function(str){
return _s.titleize(str.replace(/_/g, ' ')).replace(/\s/g, '')
},
humanize: function(str){
return _s.capitalize(this.underscored(str).replace(/_id$/,'').replace(/_/g, ' '));
},
trim: function(str, characters){
str += '';
if (!characters && nativeTrim) {
return nativeTrim.call(str);
}
characters = defaultToWhiteSpace(characters);
return str.replace(new RegExp('\^' + characters + '+|' + characters + '+$', 'g'), '');
},
ltrim: function(str, characters){
if (!characters && nativeTrimLeft) {
return nativeTrimLeft.call(str);
}
characters = defaultToWhiteSpace(characters);
return (''+str).replace(new RegExp('\^' + characters + '+', 'g'), '');
},
rtrim: function(str, characters){
if (!characters && nativeTrimRight) {
return nativeTrimRight.call(str);
}
characters = defaultToWhiteSpace(characters);
return (''+str).replace(new RegExp(characters + '+$', 'g'), '');
},
truncate: function(str, length, truncateStr){
str += ''; truncateStr = truncateStr || '...';
length = ~~length;
return str.length > length ? str.slice(0, length) + truncateStr : str;
},
/**
* _s.prune: a more elegant version of truncate
* prune extra chars, never leaving a half-chopped word.
* @author github.com/sergiokas
*/
prune: function(str, length, pruneStr){
str += ''; length = ~~length;
pruneStr = pruneStr != null ? ''+pruneStr : '...';
var pruned, borderChar, template = str.replace(/\W/g, function(ch){
return (ch.toUpperCase() !== ch.toLowerCase()) ? 'A' : ' ';
});
borderChar = template.charAt(length);
pruned = template.slice(0, length);
// Check if we're in the middle of a word
if (borderChar && borderChar.match(/\S/))
pruned = pruned.replace(/\s\S+$/, '');
pruned = _s.rtrim(pruned);
return (pruned+pruneStr).length > str.length ? str : str.substring(0, pruned.length)+pruneStr;
},
words: function(str, delimiter) {
return _s.trim(str, delimiter).split(delimiter || /\s+/);
},
pad: function(str, length, padStr, type) {
str += '';
var padding = '', padlen = 0;
length = ~~length;
if (!padStr) {
padStr = ' ';
} else if (padStr.length > 1) {
padStr = padStr.charAt(0);
}
switch(type) {
case 'right':
padlen = (length - str.length);
padding = strRepeat(padStr, padlen);
str = str+padding;
break;
case 'both':
padlen = (length - str.length);
padding = {
'left' : strRepeat(padStr, Math.ceil(padlen/2)),
'right': strRepeat(padStr, Math.floor(padlen/2))
};
str = padding.left+str+padding.right;
break;
default: // 'left'
padlen = (length - str.length);
padding = strRepeat(padStr, padlen);;
str = padding+str;
}
return str;
},
lpad: function(str, length, padStr) {
return _s.pad(str, length, padStr);
},
rpad: function(str, length, padStr) {
return _s.pad(str, length, padStr, 'right');
},
lrpad: function(str, length, padStr) {
return _s.pad(str, length, padStr, 'both');
},
sprintf: sprintf,
vsprintf: function(fmt, argv){
argv.unshift(fmt);
return sprintf.apply(null, argv);
},
toNumber: function(str, decimals) {
var num = parseNumber(parseNumber(str).toFixed(~~decimals));
return num === 0 && ''+str !== '0' ? Number.NaN : num;
},
strRight: function(str, sep){
str += ''; sep = sep != null ? ''+sep : sep;
var pos = (!sep) ? -1 : str.indexOf(sep);
return (pos != -1) ? str.slice(pos+sep.length, str.length) : str;
},
strRightBack: function(str, sep){
str += ''; sep = sep != null ? ''+sep : sep;
var pos = (!sep) ? -1 : str.lastIndexOf(sep);
return (pos != -1) ? str.slice(pos+sep.length, str.length) : str;
},
strLeft: function(str, sep){
str += ''; sep = sep != null ? ''+sep : sep;
var pos = (!sep) ? -1 : str.indexOf(sep);
return (pos != -1) ? str.slice(0, pos) : str;
},
strLeftBack: function(str, sep){
str += ''; sep = sep != null ? ''+sep : sep;
var pos = str.lastIndexOf(sep);
return (pos != -1) ? str.slice(0, pos) : str;
},
toSentence: function(array, separator, lastSeparator) {
separator || (separator = ', ');
lastSeparator || (lastSeparator = ' and ');
var length = array.length, str = '';
for (var i = 0; i < length; i++) {
str += array[i];
if (i === (length - 2)) { str += lastSeparator; }
else if (i < (length - 1)) { str += separator; }
}
return str;
},
slugify: function(str) {
var from = "ąàáäâãćęèéëêìíïîłńòóöôõùúüûñçżź·/_:;",
to = "aaaaaaceeeeeiiiilnooooouuuunczz",
regex = new RegExp(defaultToWhiteSpace(from), 'g');
str = (''+str).toLowerCase();
str = str.replace(regex, function(ch){
var index = from.indexOf(ch);
return to.charAt(index) || '-';
});
return _s.trim(str.replace(/[^\w\s-]/g, '').replace(/[-\s]+/g, '-'), '-');
},
exports: function() {
var result = {};
for (var prop in this) {
if (!this.hasOwnProperty(prop) || prop == 'include' || prop == 'contains' || prop == 'reverse') continue;
result[prop] = this[prop];
}
return result;
},
repeat: strRepeat
};
// Aliases
_s.strip = _s.trim;
_s.lstrip = _s.ltrim;
_s.rstrip = _s.rtrim;
_s.center = _s.lrpad;
_s.rjust = _s.lpad;
_s.ljust = _s.rpad;
_s.contains = _s.include;
// CommonJS module is defined
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
// Export module
module.exports = _s;
}
exports._s = _s;
} else if (typeof define === 'function' && define.amd) {
// Register as a named module with AMD.
define('underscore.string', function() {
return _s;
});
// Integrate with Underscore.js
} else if (typeof root._ !== 'undefined') {
// root._.mixin(_s);
root._.string = _s;
root._.str = root._.string;
// Or define it
} else {
root._ = {
string: _s,
str: _s
};
}
}(this || window));