forked from andrewplummer/Sugar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
string.js
1407 lines (1308 loc) · 38.5 KB
/
string.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
'use strict';
/***
* @module String
* @description String manupulation, encoding, truncation, and formatting, and more.
*
***/
// Flag allowing native string methods to be enhanced.
var STRING_ENHANCEMENTS_FLAG = 'enhanceString';
// Matches non-punctuation characters except apostrophe for capitalization.
var CAPITALIZE_REG = /[^\u0000-\u0040\u005B-\u0060\u007B-\u007F]+('s)?/g;
// Regex matching camelCase.
var CAMELIZE_REG = /(^|_)([^_]+)/g;
// Regex matching any HTML entity.
var HTML_ENTITY_REG = /&#?(x)?([\w\d]{0,5});/gi;
// Very basic HTML escaping regex.
var HTML_ESCAPE_REG = /[&<>]/g;
// Special HTML entities.
var HTMLFromEntityMap = {
'lt': '<',
'gt': '>',
'amp': '&',
'nbsp': ' ',
'quot': '"',
'apos': "'"
};
var HTMLToEntityMap;
// Words that should not be capitalized in titles
var DOWNCASED_WORDS = [
'and', 'or', 'nor', 'a', 'an', 'the', 'so', 'but', 'to', 'of', 'at',
'by', 'from', 'into', 'on', 'onto', 'off', 'out', 'in', 'over',
'with', 'for'
];
// HTML tags that do not have inner content.
var HTML_VOID_ELEMENTS = [
'area','base','br','col','command','embed','hr','img',
'input','keygen','link','meta','param','source','track','wbr'
];
var LEFT_TRIM_REG = RegExp('^['+ TRIM_CHARS +']+');
var RIGHT_TRIM_REG = RegExp('['+ TRIM_CHARS +']+$');
var TRUNC_REG = RegExp('(?=[' + TRIM_CHARS + '])');
// Reference to native String#includes to enhance later.
var nativeIncludes = String.prototype.includes;
// Base64
var encodeBase64, decodeBase64;
// Format matcher for String#format.
var stringFormatMatcher = createFormatMatcher(deepGetProperty);
function padString(num, padding) {
return repeatString(isDefined(padding) ? padding : ' ', num);
}
function truncateString(str, length, from, ellipsis, split) {
var str1, str2, len1, len2;
if (str.length <= length) {
return str.toString();
}
ellipsis = isUndefined(ellipsis) ? '...' : ellipsis;
switch(from) {
case 'left':
str2 = split ? truncateOnWord(str, length, true) : str.slice(str.length - length);
return ellipsis + str2;
case 'middle':
len1 = ceil(length / 2);
len2 = floor(length / 2);
str1 = split ? truncateOnWord(str, len1) : str.slice(0, len1);
str2 = split ? truncateOnWord(str, len2, true) : str.slice(str.length - len2);
return str1 + ellipsis + str2;
default:
str1 = split ? truncateOnWord(str, length) : str.slice(0, length);
return str1 + ellipsis;
}
}
function stringEach(str, search, fn) {
var chunks, chunk, reg, result = [];
if (isFunction(search)) {
fn = search;
reg = /[\s\S]/g;
} else if (!search) {
reg = /[\s\S]/g;
} else if (isString(search)) {
reg = RegExp(escapeRegExp(search), 'gi');
} else if (isRegExp(search)) {
reg = RegExp(search.source, getRegExpFlags(search, 'g'));
}
// Getting the entire array of chunks up front as we need to
// pass this into the callback function as an argument.
chunks = runGlobalMatch(str, reg);
if (chunks) {
for(var i = 0, len = chunks.length, r; i < len; i++) {
chunk = chunks[i];
result[i] = chunk;
if (fn) {
r = fn.call(str, chunk, i, chunks);
if (r === false) {
break;
} else if (isDefined(r)) {
result[i] = r;
}
}
}
}
return result;
}
// "match" in < IE9 has enumable properties that will confuse for..in
// loops, so ensure that the match is a normal array by manually running
// "exec". Note that this method is also slightly more performant.
function runGlobalMatch(str, reg) {
var result = [], match, lastLastIndex;
while ((match = reg.exec(str)) != null) {
if (reg.lastIndex === lastLastIndex) {
reg.lastIndex += 1;
} else {
result.push(match[0]);
}
lastLastIndex = reg.lastIndex;
}
return result;
}
function eachWord(str, fn) {
return stringEach(trim(str), /\S+/g, fn);
}
function stringCodes(str, fn) {
var codes = new Array(str.length), i, len;
for(i = 0, len = str.length; i < len; i++) {
var code = str.charCodeAt(i);
codes[i] = code;
if (fn) {
fn.call(str, code, i, str);
}
}
return codes;
}
function stringUnderscore(str) {
var areg = Inflections.acronyms && Inflections.acronyms.reg;
// istanbul ignore if
if (areg) {
str = str.replace(areg, function(acronym, index) {
return (index > 0 ? '_' : '') + acronym.toLowerCase();
})
}
return str
.replace(/[-\s]+/g, '_')
.replace(/([A-Z\d]+)([A-Z][a-z])/g,'$1_$2')
.replace(/([a-z\d])([A-Z])/g,'$1_$2')
.toLowerCase();
}
function stringCamelize(str, upper) {
str = stringUnderscore(str);
return str.replace(CAMELIZE_REG, function(match, pre, word, index) {
var cap = upper !== false || index > 0, acronym;
acronym = getAcronym(word);
// istanbul ignore if
if (acronym && cap) {
return acronym;
}
return cap ? stringCapitalize(word, true) : word;
});
}
function stringSpacify(str) {
return stringUnderscore(str).replace(/_/g, ' ');
}
function stringCapitalize(str, downcase, all) {
if (downcase) {
str = str.toLowerCase();
}
return all ? str.replace(CAPITALIZE_REG, simpleCapitalize) : simpleCapitalize(str);
}
function stringTitleize(str) {
var fullStopPunctuation = /[.:;!]$/, lastHadPunctuation;
str = runHumanRules(str);
str = stringSpacify(str);
return eachWord(str, function(word, index, words) {
word = getHumanWord(word) || word;
word = getAcronym(word) || word;
var hasPunctuation, isFirstOrLast;
var first = index == 0, last = index == words.length - 1;
hasPunctuation = fullStopPunctuation.test(word);
isFirstOrLast = first || last || hasPunctuation || lastHadPunctuation;
lastHadPunctuation = hasPunctuation;
if (isFirstOrLast || indexOf(DOWNCASED_WORDS, word) === -1) {
return stringCapitalize(word, false, true);
} else {
return word;
}
}).join(' ');
}
function stringParameterize(str, separator) {
if (separator === undefined) separator = '-';
str = str.replace(/[^a-z0-9\-_]+/gi, separator);
if (separator) {
var reg = RegExp('^{s}+|{s}+$|({s}){s}+'.split('{s}').join(escapeRegExp(separator)), 'g');
str = str.replace(reg, '$1');
}
return encodeURI(str.toLowerCase());
}
function reverseString(str) {
return str.split('').reverse().join('');
}
function truncateOnWord(str, limit, fromLeft) {
if (fromLeft) {
return reverseString(truncateOnWord(reverseString(str), limit));
}
var words = str.split(TRUNC_REG);
var count = 0;
return filter(words, function(word) {
count += word.length;
return count <= limit;
}).join('');
}
function unescapeHTML(str) {
return str.replace(HTML_ENTITY_REG, function(full, hex, code) {
var special = HTMLFromEntityMap[code];
return special || chr(hex ? parseInt(code, 16) : +code);
});
}
function tagIsVoid(tag) {
return indexOf(HTML_VOID_ELEMENTS, tag.toLowerCase()) !== -1;
}
function stringReplaceAll(str, f, replace) {
var i = 0, tokens;
if (isString(f)) {
f = RegExp(escapeRegExp(f), 'g');
} else if (f && !f.global) {
f = RegExp(f.source, getRegExpFlags(f, 'g'));
}
if (!replace) {
replace = '';
} else {
tokens = replace;
replace = function() {
var t = tokens[i++];
return t != null ? t : '';
};
}
return str.replace(f, replace);
}
function replaceTags(str, find, replacement, strip) {
var tags = isString(find) ? [find] : find, reg, src;
tags = map(tags || [], function(t) {
return escapeRegExp(t);
}).join('|');
src = tags.replace('all', '') || '[^\\s>]+';
src = '<(\\/)?(' + src + ')(\\s+[^<>]*?)?\\s*(\\/)?>';
reg = RegExp(src, 'gi');
return runTagReplacements(str.toString(), reg, strip, replacement);
}
function runTagReplacements(str, reg, strip, replacement, fullString) {
var match;
var result = '';
var currentIndex = 0;
var openTagName;
var openTagAttributes;
var openTagCount = 0;
function processTag(index, tagName, attributes, tagLength, isVoid) {
var content = str.slice(currentIndex, index), s = '', r = '';
if (isString(replacement)) {
r = replacement;
} else if (replacement) {
r = replacement.call(fullString, tagName, content, attributes, fullString) || '';
}
if (strip) {
s = r;
} else {
content = r;
}
if (content) {
content = runTagReplacements(content, reg, strip, replacement, fullString);
}
result += s + content + (isVoid ? '' : s);
currentIndex = index + (tagLength || 0);
}
fullString = fullString || str;
reg = RegExp(reg.source, 'gi');
while(match = reg.exec(str)) {
var tagName = match[2];
var attributes = (match[3]|| '').slice(1);
var isClosingTag = !!match[1];
var isSelfClosing = !!match[4];
var tagLength = match[0].length;
var isVoid = tagIsVoid(tagName);
var isOpeningTag = !isClosingTag && !isSelfClosing && !isVoid;
var isSameAsCurrent = tagName === openTagName;
if (!openTagName) {
result += str.slice(currentIndex, match.index);
currentIndex = match.index;
}
if (isOpeningTag) {
if (!openTagName) {
openTagName = tagName;
openTagAttributes = attributes;
openTagCount++;
currentIndex += tagLength;
} else if (isSameAsCurrent) {
openTagCount++;
}
} else if (isClosingTag && isSameAsCurrent) {
openTagCount--;
if (openTagCount === 0) {
processTag(match.index, openTagName, openTagAttributes, tagLength, isVoid);
openTagName = null;
openTagAttributes = null;
}
} else if (!openTagName) {
processTag(match.index, tagName, attributes, tagLength, isVoid);
}
}
if (openTagName) {
processTag(str.length, openTagName, openTagAttributes);
}
result += str.slice(currentIndex);
return result;
}
function numberOrIndex(str, n, from) {
if (isString(n)) {
n = str.indexOf(n);
if (n === -1) {
n = from ? str.length : 0;
}
}
return n;
}
function buildBase64() {
var encodeAscii, decodeAscii;
// istanbul ignore next
function catchEncodingError(fn) {
return function(str) {
try {
return fn(str);
} catch(e) {
return '';
}
};
}
// istanbul ignore if
if (typeof Buffer !== 'undefined') {
encodeBase64 = function(str) {
return Buffer.from(str).toString('base64');
};
decodeBase64 = function(str) {
return Buffer.from(str, 'base64').toString('utf8');
};
return;
}
// istanbul ignore if
if (typeof btoa !== 'undefined') {
encodeAscii = catchEncodingError(btoa);
decodeAscii = catchEncodingError(atob);
} else {
var key = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
var base64reg = /[^A-Za-z0-9\+\/\=]/g;
encodeAscii = function(str) {
var output = '';
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
do {
chr1 = str.charCodeAt(i++);
chr2 = str.charCodeAt(i++);
chr3 = str.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output += key.charAt(enc1);
output += key.charAt(enc2);
output += key.charAt(enc3);
output += key.charAt(enc4);
chr1 = chr2 = chr3 = '';
enc1 = enc2 = enc3 = enc4 = '';
} while (i < str.length);
return output;
};
decodeAscii = function(input) {
var output = '';
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
if (input.match(base64reg)) {
return '';
}
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, '');
do {
enc1 = key.indexOf(input.charAt(i++));
enc2 = key.indexOf(input.charAt(i++));
enc3 = key.indexOf(input.charAt(i++));
enc4 = key.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + chr(chr1);
if (enc3 != 64) {
output = output + chr(chr2);
}
if (enc4 != 64) {
output = output + chr(chr3);
}
chr1 = chr2 = chr3 = '';
enc1 = enc2 = enc3 = enc4 = '';
} while (i < input.length);
return output;
};
}
encodeBase64 = function(str) {
return encodeAscii(unescape(encodeURIComponent(str)));
};
decodeBase64 = function(str) {
return decodeURIComponent(escape(decodeAscii(str)));
};
}
function buildEntities() {
HTMLToEntityMap = {};
forEachProperty(HTMLFromEntityMap, function(val, key) {
HTMLToEntityMap[val] = '&' + key + ';';
});
}
function callIncludesWithRegexSupport(str, search, position) {
if (!isRegExp(search)) {
return nativeIncludes.call(str, search, position);
}
if (position) {
str = str.slice(position);
}
return search.test(str);
}
defineInstance(sugarString, {
// Enhancment to String#includes to allow a regex.
'includes': fixArgumentLength(callIncludesWithRegexSupport)
}, [ENHANCEMENTS_FLAG, STRING_ENHANCEMENTS_FLAG]);
defineInstance(sugarString, {
/***
* @method at(index, [loop] = false)
* @returns Mixed
* @short Gets the character(s) at a given index.
* @extra When [loop] is true, overshooting the end of the string will begin
* counting from the other end. `index` may be negative. If `index` is
* an array, multiple elements will be returned.
* @example
*
* 'jumpy'.at(0) -> 'j'
* 'jumpy'.at(2) -> 'm'
* 'jumpy'.at(5) -> ''
* 'jumpy'.at(5, true) -> 'j'
* 'jumpy'.at(-1) -> 'y'
* 'lucky charms'.at([2, 4]) -> ['u','k']
*
* @param {number|Array<number>} index
* @param {boolean} [loop]
*
***/
'at': function(str, index, loop) {
return getEntriesForIndexes(str, index, loop, true);
},
/***
* @method escapeURL([param] = false)
* @returns String
* @short Escapes characters in a string to make a valid URL.
* @extra If [param] is true, it will also escape valid URL characters. Use
* this when the entire string is meant for use in a query string.
*
* @example
*
* 'a, b, and c'.escapeURL() -> 'a,%20b,%20and%20c'
* 'http://foo.com/'.escapeURL(true) -> 'http%3A%2F%2Ffoo.com%2F'
*
* @param {boolean} [param]
*
***/
'escapeURL': function(str, param) {
return param ? encodeURIComponent(str) : encodeURI(str);
},
/***
* @method unescapeURL([partial] = false)
* @returns String
* @short Restores escaped characters in a URL escaped string.
* @extra If [partial] is true, it will only unescape non-valid URL tokens,
* and is included here for completeness, but should be rarely needed.
*
* @example
*
* 'http%3A%2F%2Ffoo.com%2F'.unescapeURL() -> 'http://foo.com/'
* 'http%3A%2F%2Ffoo.com%2F'.unescapeURL(true) -> 'http%3A%2F%2Ffoo.com%2F'
*
* @param {boolean} [partial]
*
***/
'unescapeURL': function(str, param) {
return param ? decodeURI(str) : decodeURIComponent(str);
},
/***
* @method escapeHTML()
* @returns String
* @short Converts HTML characters to their entity equivalents.
*
* @example
*
* '<p>some text</p>'.escapeHTML() -> '<p>some text</p>'
* 'one & two'.escapeHTML() -> 'one & two'
*
***/
'escapeHTML': function(str) {
return str.replace(HTML_ESCAPE_REG, function(chr) {
return getOwn(HTMLToEntityMap, chr);
});
},
/***
* @method unescapeHTML()
* @returns String
* @short Restores escaped HTML characters.
*
* @example
*
* '<p>some text</p>'.unescapeHTML() -> '<p>some text</p>'
* 'one & two'.unescapeHTML() -> 'one & two'
*
***/
'unescapeHTML': function(str) {
return unescapeHTML(str);
},
/***
* @method stripTags([tag] = 'all', [replace])
* @returns String
* @short Strips HTML tags from the string.
* @extra [tag] may be an array of tags or 'all', in which case all tags will
* be stripped. [replace] will replace what was stripped, and may be a
* string or a function of type `replaceFn` to handle replacements. If
* this function returns a string, then it will be used for the
* replacement. If it returns `undefined`, the tags will be stripped normally.
*
* @callback replaceFn
*
* tag The tag name.
* inner The tag content.
* attr The attributes on the tag, if any, as a string.
* outer The entire matched tag string.
*
* @example
*
* '<p>just <b>some</b> text</p>'.stripTags() -> 'just some text'
* '<p>just <b>some</b> text</p>'.stripTags('p') -> 'just <b>some</b> text'
* '<p>hi!</p>'.stripTags('p', function(all, content) {
* return '|';
* }); -> '|hi!|'
*
* @param {string} tag
* @param {string|replaceFn} replace
* @callbackParam {string} tag
* @callbackParam {string} inner
* @callbackParam {string} attr
* @callbackParam {string} outer
* @callbackReturns {string} replaceFn
*
***/
'stripTags': function(str, tag, replace) {
return replaceTags(str, tag, replace, true);
},
/***
* @method removeTags([tag] = 'all', [replace])
* @returns String
* @short Removes HTML tags and their contents from the string.
* @extra [tag] may be an array of tags or 'all', in which case all tags will
* be removed. [replace] will replace what was removed, and may be a
* string or a function of type `replaceFn` to handle replacements. If
* this function returns a string, then it will be used for the
* replacement. If it returns `undefined`, the tags will be removed normally.
*
* @callback replaceFn
*
* tag The tag name.
* inner The tag content.
* attr The attributes on the tag, if any, as a string.
* outer The entire matched tag string.
*
* @example
*
* '<p>just <b>some</b> text</p>'.removeTags() -> ''
* '<p>just <b>some</b> text</p>'.removeTags('b') -> '<p>just text</p>'
* '<p>hi!</p>'.removeTags('p', function(all, content) {
* return 'bye!';
* }); -> 'bye!'
*
* @param {string} tag
* @param {string|replaceFn} replace
* @callbackParam {string} tag
* @callbackParam {string} inner
* @callbackParam {string} attr
* @callbackParam {string} outer
* @callbackReturns {string} replaceFn
*
***/
'removeTags': function(str, tag, replace) {
return replaceTags(str, tag, replace, false);
},
/***
* @method encodeBase64()
* @returns String
* @short Encodes the string into base64 encoding.
* @extra This method wraps native methods when available, and uses a custom
* implementation when not available. It can also handle Unicode
* string encodings.
*
* @example
*
* 'gonna get encoded!'.encodeBase64() -> 'Z29ubmEgZ2V0IGVuY29kZWQh'
* 'http://twitter.com/'.encodeBase64() -> 'aHR0cDovL3R3aXR0ZXIuY29tLw=='
*
***/
'encodeBase64': function(str) {
return encodeBase64(str);
},
/***
* @method decodeBase64()
* @returns String
* @short Decodes the string from base64 encoding.
* @extra This method wraps native methods when available, and uses a custom
* implementation when not available. It can also handle Unicode string
* encodings.
*
* @example
*
* 'aHR0cDovL3R3aXR0ZXIuY29tLw=='.decodeBase64() -> 'http://twitter.com/'
* 'anVzdCBnb3QgZGVjb2RlZA=='.decodeBase64() -> 'just got decoded!'
*
***/
'decodeBase64': function(str) {
return decodeBase64(str);
},
/***
* @method forEach([search], [eachFn])
* @returns Array
* @short Runs callback [eachFn] against every character in the string, or
* every every occurence of [search] if it is provided.
* @extra Returns an array of matches. [search] may be either a string or
* regex, and defaults to every character in the string. If [eachFn]
* returns false at any time it will break out of the loop.
*
* @callback eachFn
*
* match The current match.
* i The current index.
* arr An array of all matches.
*
* @example
*
* 'jumpy'.forEach(log) -> ['j','u','m','p','y']
* 'jumpy'.forEach(/[r-z]/) -> ['u','y']
* 'jumpy'.forEach(/mp/) -> ['mp']
* 'jumpy'.forEach(/[r-z]/, function(m) {
* // Called twice: "u", "y"
* });
*
* @signature forEach(eachFn)
* @param {string|RegExp} [search]
* @param {eachFn} [eachFn]
* @callbackParam {string} match
* @callbackParam {number} i
* @callbackParam {Array<string>} arr
*
***/
'forEach': function(str, search, eachFn) {
return stringEach(str, search, eachFn);
},
/***
* @method chars([eachCharFn])
* @returns Array
* @short Runs [eachCharFn] against each character in the string, and returns an array.
*
* @callback eachCharFn
*
* char The current character.
* i The current index.
* arr An array of all characters.
*
* @example
*
* 'jumpy'.chars() -> ['j','u','m','p','y']
* 'jumpy'.chars(function(c) {
* // Called 5 times: "j","u","m","p","y"
* });
*
* @param {eachCharFn} [eachCharFn]
* @callbackParam {string} char
* @callbackParam {number} i
* @callbackParam {Array<string>} arr
*
***/
'chars': function(str, search, eachCharFn) {
return stringEach(str, search, eachCharFn);
},
/***
* @method words([eachWordFn])
* @returns Array
* @short Runs [eachWordFn] against each word in the string, and returns an array.
* @extra A "word" is defined as any sequence of non-whitespace characters.
*
* @callback eachWordFn
*
* word The current word.
* i The current index.
* arr An array of all words.
*
* @example
*
* 'broken wear'.words() -> ['broken','wear']
* 'broken wear'.words(function(w) {
* // Called twice: "broken", "wear"
* });
*
* @param {eachWordFn} [eachWordFn]
* @callbackParam {string} word
* @callbackParam {number} i
* @callbackParam {Array<string>} arr
*
***/
'words': function(str, eachWordFn) {
return stringEach(trim(str), /\S+/g, eachWordFn);
},
/***
* @method lines([eachLineFn])
* @returns Array
* @short Runs [eachLineFn] against each line in the string, and returns an array.
*
* @callback eachLineFn
*
* line The current line.
* i The current index.
* arr An array of all lines.
*
* @example
*
* lineText.lines() -> array of lines
* lineText.lines(function(l) {
* // Called once per line
* });
*
* @param {eachLineFn} [eachLineFn]
* @callbackParam {string} line
* @callbackParam {number} i
* @callbackParam {Array<string>} arr
*
***/
'lines': function(str, eachLineFn) {
return stringEach(trim(str), /^.*$/gm, eachLineFn);
},
/***
* @method codes([eachCodeFn])
* @returns Array
* @short Runs callback [eachCodeFn] against each character code in the string.
* Returns an array of character codes.
*
* @callback eachCodeFn
*
* code The current character code.
* i The current index.
* str The string being operated on.
*
* @example
*
* 'jumpy'.codes() -> [106,117,109,112,121]
* 'jumpy'.codes(function(c) {
* // Called 5 times: 106, 117, 109, 112, 121
* });
*
* @param {eachCodeFn} [eachCodeFn]
* @callbackParam {number} code
* @callbackParam {number} i
* @callbackParam {string} str
*
***/
'codes': function(str, eachCodeFn) {
return stringCodes(str, eachCodeFn);
},
/***
* @method shift(n)
* @returns Array
* @short Shifts each character in the string `n` places in the character map.
*
* @example
*
* 'a'.shift(1) -> 'b'
* 'ク'.shift(1) -> 'グ'
*
* @param {number} n
*
***/
'shift': function(str, n) {
var result = '';
n = n || 0;
stringCodes(str, function(c) {
result += chr(c + n);
});
return result;
},
/***
* @method isBlank()
* @returns Boolean
* @short Returns true if the string has length 0 or contains only whitespace.
*
* @example
*
* ''.isBlank() -> true
* ' '.isBlank() -> true
* 'noway'.isBlank() -> false
*
***/
'isBlank': function(str) {
return trim(str).length === 0;
},
/***
* @method isEmpty()
* @returns Boolean
* @short Returns true if the string has length 0.
*
* @example
*
* ''.isEmpty() -> true
* 'a'.isBlank() -> false
* ' '.isBlank() -> false
*
***/
'isEmpty': function(str) {
return str.length === 0;
},
/***
* @method insert(str, [index] = length)
* @returns String
* @short Adds `str` at [index]. Allows negative values.
*
* @example
*
* 'dopamine'.insert('e', 3) -> dopeamine
* 'spelling eror'.insert('r', -3) -> spelling error
*
* @param {string} str
* @param {number} [index]
*
***/
'insert': function(str, substr, index) {
index = isUndefined(index) ? str.length : index;
return str.slice(0, index) + substr + str.slice(index);
},
/***
* @method remove(f)
* @returns String
* @short Removes the first occurrence of `f` in the string.
* @extra `f` can be a either case-sensitive string or a regex. In either case
* only the first match will be removed. To remove multiple occurrences,
* use `removeAll`.
*
* @example
*
* 'schfifty five'.remove('f') -> 'schifty five'
* 'schfifty five'.remove(/[a-f]/g) -> 'shfifty five'
*
* @param {string|RegExp} f
*
***/
'remove': function(str, f) {
return str.replace(f, '');
},
/***
* @method removeAll(f)
* @returns String
* @short Removes any occurences of `f` in the string.
* @extra `f` can be either a case-sensitive string or a regex. In either case
* all matches will be removed. To remove only a single occurence, use
* `remove`.
*
* @example
*
* 'schfifty five'.removeAll('f') -> 'schity ive'
* 'schfifty five'.removeAll(/[a-f]/) -> 'shity iv'
*
* @param {string|RegExp} f
*
***/
'removeAll': function(str, f) {
return stringReplaceAll(str, f);
},
/***
* @method reverse()
* @returns String
* @short Reverses the string.
*
* @example
*
* 'jumpy'.reverse() -> 'ypmuj'
* 'lucky charms'.reverse() -> 'smrahc ykcul'
*
***/
'reverse': function(str) {
return reverseString(str);
},
/***
* @method compact()
* @returns String
* @short Compacts whitespace in the string to a single space and trims the ends.
*
* @example
*
* 'too \n much \n space'.compact() -> 'too much space'
* 'enough \n '.compact() -> 'enought'
*
***/
'compact': function(str) {
return trim(str).replace(/([\r\n\s ])+/g, function(match, whitespace) {
return whitespace === ' ' ? whitespace : ' ';
});
},
/***
* @method from([index] = 0)
* @returns String
* @short Returns a section of the string starting from [index].
*
* @example
*
* 'lucky charms'.from() -> 'lucky charms'
* 'lucky charms'.from(7) -> 'harms'
*
* @param {number} [index]
*
***/
'from': function(str, from) {