3 @class Additions to the core string object.
6 /** @author Steven Levithan, released as public domain. */
7 String
.prototype.trim
= function() {
8 var str
= this.replace(/^\s+/, '');
9 for (var i
= str
.length
- 1; i
>= 0; i
--) {
10 if (/\S/.test(str
.charAt(i
))) {
11 str
= str
.substring(0, i
+ 1);
18 plan(6, "Testing String.prototype.trim.");
20 var s = " a bc ".trim();
21 is(s, "a bc", "multiple spaces front and back are trimmed.");
23 s = "a bc\n\n".trim();
24 is(s, "a bc", "newlines only in back are trimmed.");
27 is(s, "a bc", "tabs only in front are trimmed.");
30 is(s, "", "an all-space string is trimmed to empty.");
33 is(s, "a b\nc", "a string with no spaces in front or back is trimmed to itself.");
36 is(s, "", "an empty string is trimmed to empty.");
40 String
.prototype.balance
= function(open
, close
) {
42 while (this.charAt(i
) != open
) {
43 if (i
== this.length
) return [-1, -1];
49 while (j
< this.length
) {
50 if (this.charAt(j
) == open
) balance
++;
51 if (this.charAt(j
) == close
) balance
--;
52 if (balance
== 0) break;
54 if (j
== this.length
) return [-1, -1];
60 plan(16, "Testing String.prototype.balance.");
62 var s = "{abc}".balance("{","}");
63 is(s[0], 0, "opener in first is found.");
64 is(s[1], 4, "closer in last is found.");
66 s = "ab{c}de".balance("{","}");
67 is(s[0], 2, "opener in middle is found.");
68 is(s[1], 4, "closer in middle is found.");
70 s = "a{b{c}de}f".balance("{","}");
71 is(s[0], 1, "nested opener is found.");
72 is(s[1], 8, "nested closer is found.");
74 s = "{}".balance("{","}");
75 is(s[0], 0, "opener with no content is found.");
76 is(s[1], 1, "closer with no content is found.");
78 s = "".balance("{","}");
79 is(s[0], -1, "empty string opener is -1.");
80 is(s[1], -1, "empty string closer is -1.");
82 s = "{abc".balance("{","}");
83 is(s[0], -1, "opener with no closer returns -1.");
84 is(s[1], -1, "no closer returns -1.");
86 s = "abc".balance("{","}");
87 is(s[0], -1, "no opener or closer returns -1 for opener.");
88 is(s[1], -1, "no opener or closer returns -1 for closer.");
90 s = "a<bc}de".balance("<","}");
91 is(s[0], 1, "unmatching opener is found.");
92 is(s[1], 4, "unmatching closer is found.");