Upgrade to ExtJS 4.0.0 - Released 04/26/2011
[extjs.git] / src / core / src / lang / String.js
1 /**
2  * @class Ext.String
3  *
4  * A collection of useful static methods to deal with strings
5  * @singleton
6  */
7
8 Ext.String = {
9     trimRegex: /^[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000]+|[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000]+$/g,
10     escapeRe: /('|\\)/g,
11     formatRe: /\{(\d+)\}/g,
12     escapeRegexRe: /([-.*+?^${}()|[\]\/\\])/g,
13
14     /**
15      * Convert certain characters (&, <, >, and ') to their HTML character equivalents for literal display in web pages.
16      * @param {String} value The string to encode
17      * @return {String} The encoded text
18      */
19     htmlEncode: (function() {
20         var entities = {
21             '&': '&amp;',
22             '>': '&gt;',
23             '<': '&lt;',
24             '"': '&quot;'
25         }, keys = [], p, regex;
26         
27         for (p in entities) {
28             keys.push(p);
29         }
30         
31         regex = new RegExp('(' + keys.join('|') + ')', 'g');
32         
33         return function(value) {
34             return (!value) ? value : String(value).replace(regex, function(match, capture) {
35                 return entities[capture];    
36             });
37         };
38     })(),
39
40     /**
41      * Convert certain characters (&, <, >, and ') from their HTML character equivalents.
42      * @param {String} value The string to decode
43      * @return {String} The decoded text
44      */
45     htmlDecode: (function() {
46         var entities = {
47             '&amp;': '&',
48             '&gt;': '>',
49             '&lt;': '<',
50             '&quot;': '"'
51         }, keys = [], p, regex;
52         
53         for (p in entities) {
54             keys.push(p);
55         }
56         
57         regex = new RegExp('(' + keys.join('|') + '|&#[0-9]{1,5};' + ')', 'g');
58         
59         return function(value) {
60             return (!value) ? value : String(value).replace(regex, function(match, capture) {
61                 if (capture in entities) {
62                     return entities[capture];
63                 } else {
64                     return String.fromCharCode(parseInt(capture.substr(2), 10));
65                 }
66             });
67         };
68     })(),
69
70     /**
71      * Appends content to the query string of a URL, handling logic for whether to place
72      * a question mark or ampersand.
73      * @param {String} url The URL to append to.
74      * @param {String} string The content to append to the URL.
75      * @return (String) The resulting URL
76      */
77     urlAppend : function(url, string) {
78         if (!Ext.isEmpty(string)) {
79             return url + (url.indexOf('?') === -1 ? '?' : '&') + string;
80         }
81
82         return url;
83     },
84
85     /**
86      * Trims whitespace from either end of a string, leaving spaces within the string intact.  Example:
87      * @example
88 var s = '  foo bar  ';
89 alert('-' + s + '-');         //alerts "- foo bar -"
90 alert('-' + Ext.String.trim(s) + '-');  //alerts "-foo bar-"
91
92      * @param {String} string The string to escape
93      * @return {String} The trimmed string
94      */
95     trim: function(string) {
96         return string.replace(Ext.String.trimRegex, "");
97     },
98
99     /**
100      * Capitalize the given string
101      * @param {String} string
102      * @return {String}
103      */
104     capitalize: function(string) {
105         return string.charAt(0).toUpperCase() + string.substr(1);
106     },
107
108     /**
109      * Truncate a string and add an ellipsis ('...') to the end if it exceeds the specified length
110      * @param {String} value The string to truncate
111      * @param {Number} length The maximum length to allow before truncating
112      * @param {Boolean} word True to try to find a common word break
113      * @return {String} The converted text
114      */
115     ellipsis: function(value, len, word) {
116         if (value && value.length > len) {
117             if (word) {
118                 var vs = value.substr(0, len - 2),
119                 index = Math.max(vs.lastIndexOf(' '), vs.lastIndexOf('.'), vs.lastIndexOf('!'), vs.lastIndexOf('?'));
120                 if (index !== -1 && index >= (len - 15)) {
121                     return vs.substr(0, index) + "...";
122                 }
123             }
124             return value.substr(0, len - 3) + "...";
125         }
126         return value;
127     },
128
129     /**
130      * Escapes the passed string for use in a regular expression
131      * @param {String} string
132      * @return {String}
133      */
134     escapeRegex: function(string) {
135         return string.replace(Ext.String.escapeRegexRe, "\\$1");
136     },
137
138     /**
139      * Escapes the passed string for ' and \
140      * @param {String} string The string to escape
141      * @return {String} The escaped string
142      */
143     escape: function(string) {
144         return string.replace(Ext.String.escapeRe, "\\$1");
145     },
146
147     /**
148      * Utility function that allows you to easily switch a string between two alternating values.  The passed value
149      * is compared to the current string, and if they are equal, the other value that was passed in is returned.  If
150      * they are already different, the first value passed in is returned.  Note that this method returns the new value
151      * but does not change the current string.
152      * <pre><code>
153     // alternate sort directions
154     sort = Ext.String.toggle(sort, 'ASC', 'DESC');
155
156     // instead of conditional logic:
157     sort = (sort == 'ASC' ? 'DESC' : 'ASC');
158        </code></pre>
159      * @param {String} string The current string
160      * @param {String} value The value to compare to the current string
161      * @param {String} other The new value to use if the string already equals the first value passed in
162      * @return {String} The new value
163      */
164     toggle: function(string, value, other) {
165         return string === value ? other : value;
166     },
167
168     /**
169      * Pads the left side of a string with a specified character.  This is especially useful
170      * for normalizing number and date strings.  Example usage:
171      *
172      * <pre><code>
173 var s = Ext.String.leftPad('123', 5, '0');
174 // s now contains the string: '00123'
175        </code></pre>
176      * @param {String} string The original string
177      * @param {Number} size The total length of the output string
178      * @param {String} character (optional) The character with which to pad the original string (defaults to empty string " ")
179      * @return {String} The padded string
180      */
181     leftPad: function(string, size, character) {
182         var result = String(string);
183         character = character || " ";
184         while (result.length < size) {
185             result = character + result;
186         }
187         return result;
188     },
189
190     /**
191      * Allows you to define a tokenized string and pass an arbitrary number of arguments to replace the tokens.  Each
192      * token must be unique, and must increment in the format {0}, {1}, etc.  Example usage:
193      * <pre><code>
194 var cls = 'my-class', text = 'Some text';
195 var s = Ext.String.format('&lt;div class="{0}">{1}&lt;/div>', cls, text);
196 // s now contains the string: '&lt;div class="my-class">Some text&lt;/div>'
197        </code></pre>
198      * @param {String} string The tokenized string to be formatted
199      * @param {String} value1 The value to replace token {0}
200      * @param {String} value2 Etc...
201      * @return {String} The formatted string
202      */
203     format: function(format) {
204         var args = Ext.Array.toArray(arguments, 1);
205         return format.replace(Ext.String.formatRe, function(m, i) {
206             return args[i];
207         });
208     }
209 };