Upgrade to ExtJS 3.2.1 - Released 04/27/2010
[extjs.git] / src / util / Format.js
1 /*!
2  * Ext JS Library 3.2.1
3  * Copyright(c) 2006-2010 Ext JS, Inc.
4  * licensing@extjs.com
5  * http://www.extjs.com/license
6  */
7 /**
8  * @class Ext.util.Format
9  * Reusable data formatting functions
10  * @singleton
11  */
12 Ext.util.Format = function(){
13     var trimRe = /^\s+|\s+$/g,
14         stripTagsRE = /<\/?[^>]+>/gi,
15         stripScriptsRe = /(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/ig,
16         nl2brRe = /\r?\n/g;
17
18     return {
19         /**
20          * Truncate a string and add an ellipsis ('...') to the end if it exceeds the specified length
21          * @param {String} value The string to truncate
22          * @param {Number} length The maximum length to allow before truncating
23          * @param {Boolean} word True to try to find a common work break
24          * @return {String} The converted text
25          */
26         ellipsis : function(value, len, word){
27             if(value && value.length > len){
28                 if(word){
29                     var vs = value.substr(0, len - 2),
30                         index = Math.max(vs.lastIndexOf(' '), vs.lastIndexOf('.'), vs.lastIndexOf('!'), vs.lastIndexOf('?'));
31                     if(index == -1 || index < (len - 15)){
32                         return value.substr(0, len - 3) + "...";
33                     }else{
34                         return vs.substr(0, index) + "...";
35                     }
36                 } else{
37                     return value.substr(0, len - 3) + "...";
38                 }
39             }
40             return value;
41         },
42
43         /**
44          * Checks a reference and converts it to empty string if it is undefined
45          * @param {Mixed} value Reference to check
46          * @return {Mixed} Empty string if converted, otherwise the original value
47          */
48         undef : function(value){
49             return value !== undefined ? value : "";
50         },
51
52         /**
53          * Checks a reference and converts it to the default value if it's empty
54          * @param {Mixed} value Reference to check
55          * @param {String} defaultValue The value to insert of it's undefined (defaults to "")
56          * @return {String}
57          */
58         defaultValue : function(value, defaultValue){
59             return value !== undefined && value !== '' ? value : defaultValue;
60         },
61
62         /**
63          * Convert certain characters (&, <, >, and ') to their HTML character equivalents for literal display in web pages.
64          * @param {String} value The string to encode
65          * @return {String} The encoded text
66          */
67         htmlEncode : function(value){
68             return !value ? value : String(value).replace(/&/g, "&amp;").replace(/>/g, "&gt;").replace(/</g, "&lt;").replace(/"/g, "&quot;");
69         },
70
71         /**
72          * Convert certain characters (&, <, >, and ') from their HTML character equivalents.
73          * @param {String} value The string to decode
74          * @return {String} The decoded text
75          */
76         htmlDecode : function(value){
77             return !value ? value : String(value).replace(/&gt;/g, ">").replace(/&lt;/g, "<").replace(/&quot;/g, '"').replace(/&amp;/g, "&");
78         },
79
80         /**
81          * Trims any whitespace from either side of a string
82          * @param {String} value The text to trim
83          * @return {String} The trimmed text
84          */
85         trim : function(value){
86             return String(value).replace(trimRe, "");
87         },
88
89         /**
90          * Returns a substring from within an original string
91          * @param {String} value The original text
92          * @param {Number} start The start index of the substring
93          * @param {Number} length The length of the substring
94          * @return {String} The substring
95          */
96         substr : function(value, start, length){
97             return String(value).substr(start, length);
98         },
99
100         /**
101          * Converts a string to all lower case letters
102          * @param {String} value The text to convert
103          * @return {String} The converted text
104          */
105         lowercase : function(value){
106             return String(value).toLowerCase();
107         },
108
109         /**
110          * Converts a string to all upper case letters
111          * @param {String} value The text to convert
112          * @return {String} The converted text
113          */
114         uppercase : function(value){
115             return String(value).toUpperCase();
116         },
117
118         /**
119          * Converts the first character only of a string to upper case
120          * @param {String} value The text to convert
121          * @return {String} The converted text
122          */
123         capitalize : function(value){
124             return !value ? value : value.charAt(0).toUpperCase() + value.substr(1).toLowerCase();
125         },
126
127         // private
128         call : function(value, fn){
129             if(arguments.length > 2){
130                 var args = Array.prototype.slice.call(arguments, 2);
131                 args.unshift(value);
132                 return eval(fn).apply(window, args);
133             }else{
134                 return eval(fn).call(window, value);
135             }
136         },
137
138         /**
139          * Format a number as US currency
140          * @param {Number/String} value The numeric value to format
141          * @return {String} The formatted currency string
142          */
143         usMoney : function(v){
144             v = (Math.round((v-0)*100))/100;
145             v = (v == Math.floor(v)) ? v + ".00" : ((v*10 == Math.floor(v*10)) ? v + "0" : v);
146             v = String(v);
147             var ps = v.split('.'),
148                 whole = ps[0],
149                 sub = ps[1] ? '.'+ ps[1] : '.00',
150                 r = /(\d+)(\d{3})/;
151             while (r.test(whole)) {
152                 whole = whole.replace(r, '$1' + ',' + '$2');
153             }
154             v = whole + sub;
155             if(v.charAt(0) == '-'){
156                 return '-$' + v.substr(1);
157             }
158             return "$" +  v;
159         },
160
161         /**
162          * Parse a value into a formatted date using the specified format pattern.
163          * @param {String/Date} value The value to format (Strings must conform to the format expected by the javascript Date object's <a href="http://www.w3schools.com/jsref/jsref_parse.asp">parse()</a> method)
164          * @param {String} format (optional) Any valid date format string (defaults to 'm/d/Y')
165          * @return {String} The formatted date string
166          */
167         date : function(v, format){
168             if(!v){
169                 return "";
170             }
171             if(!Ext.isDate(v)){
172                 v = new Date(Date.parse(v));
173             }
174             return v.dateFormat(format || "m/d/Y");
175         },
176
177         /**
178          * Returns a date rendering function that can be reused to apply a date format multiple times efficiently
179          * @param {String} format Any valid date format string
180          * @return {Function} The date formatting function
181          */
182         dateRenderer : function(format){
183             return function(v){
184                 return Ext.util.Format.date(v, format);
185             };
186         },
187
188         /**
189          * Strips all HTML tags
190          * @param {Mixed} value The text from which to strip tags
191          * @return {String} The stripped text
192          */
193         stripTags : function(v){
194             return !v ? v : String(v).replace(stripTagsRE, "");
195         },
196
197         /**
198          * Strips all script tags
199          * @param {Mixed} value The text from which to strip script tags
200          * @return {String} The stripped text
201          */
202         stripScripts : function(v){
203             return !v ? v : String(v).replace(stripScriptsRe, "");
204         },
205
206         /**
207          * Simple format for a file size (xxx bytes, xxx KB, xxx MB)
208          * @param {Number/String} size The numeric value to format
209          * @return {String} The formatted file size
210          */
211         fileSize : function(size){
212             if(size < 1024) {
213                 return size + " bytes";
214             } else if(size < 1048576) {
215                 return (Math.round(((size*10) / 1024))/10) + " KB";
216             } else {
217                 return (Math.round(((size*10) / 1048576))/10) + " MB";
218             }
219         },
220
221         /**
222          * It does simple math for use in a template, for example:<pre><code>
223          * var tpl = new Ext.Template('{value} * 10 = {value:math("* 10")}');
224          * </code></pre>
225          * @return {Function} A function that operates on the passed value.
226          */
227         math : function(){
228             var fns = {};
229             return function(v, a){
230                 if(!fns[a]){
231                     fns[a] = new Function('v', 'return v ' + a + ';');
232                 }
233                 return fns[a](v);
234             }
235         }(),
236
237         /**
238          * Rounds the passed number to the required decimal precision.
239          * @param {Number/String} value The numeric value to round.
240          * @param {Number} precision The number of decimal places to which to round the first parameter's value.
241          * @return {Number} The rounded value.
242          */
243         round : function(value, precision) {
244             var result = Number(value);
245             if (typeof precision == 'number') {
246                 precision = Math.pow(10, precision);
247                 result = Math.round(value * precision) / precision;
248             }
249             return result;
250         },
251
252         /**
253          * Formats the number according to the format string.
254          * <div style="margin-left:40px">examples (123456.789):
255          * <div style="margin-left:10px">
256          * 0 - (123456) show only digits, no precision<br>
257          * 0.00 - (123456.78) show only digits, 2 precision<br>
258          * 0.0000 - (123456.7890) show only digits, 4 precision<br>
259          * 0,000 - (123,456) show comma and digits, no precision<br>
260          * 0,000.00 - (123,456.78) show comma and digits, 2 precision<br>
261          * 0,0.00 - (123,456.78) shortcut method, show comma and digits, 2 precision<br>
262          * To reverse the grouping (,) and decimal (.) for international numbers, add /i to the end.
263          * For example: 0.000,00/i
264          * </div></div>
265          * @param {Number} v The number to format.
266          * @param {String} format The way you would like to format this text.
267          * @return {String} The formatted number.
268          */
269         number: function(v, format) {
270             if(!format){
271                 return v;
272             }
273             v = Ext.num(v, NaN);
274             if (isNaN(v)){
275                 return '';
276             }
277             var comma = ',',
278                 dec = '.',
279                 i18n = false,
280                 neg = v < 0;
281
282             v = Math.abs(v);
283             if(format.substr(format.length - 2) == '/i'){
284                 format = format.substr(0, format.length - 2);
285                 i18n = true;
286                 comma = '.';
287                 dec = ',';
288             }
289
290             var hasComma = format.indexOf(comma) != -1,
291                 psplit = (i18n ? format.replace(/[^\d\,]/g, '') : format.replace(/[^\d\.]/g, '')).split(dec);
292
293             if(1 < psplit.length){
294                 v = v.toFixed(psplit[1].length);
295             }else if(2 < psplit.length){
296                 throw ('NumberFormatException: invalid format, formats should have no more than 1 period: ' + format);
297             }else{
298                 v = v.toFixed(0);
299             }
300
301             var fnum = v.toString();
302
303             psplit = fnum.split('.');
304
305             if (hasComma) {
306                 var cnum = psplit[0], parr = [], j = cnum.length, m = Math.floor(j / 3), n = cnum.length % 3 || 3;
307
308                 for (var i = 0; i < j; i += n) {
309                     if (i != 0) {
310                         n = 3;
311                     }
312                     parr[parr.length] = cnum.substr(i, n);
313                     m -= 1;
314                 }
315                 fnum = parr.join(comma);
316                 if (psplit[1]) {
317                     fnum += dec + psplit[1];
318                 }
319             } else {
320                 if (psplit[1]) {
321                     fnum = psplit[0] + dec + psplit[1];
322                 }
323             }
324
325             return (neg ? '-' : '') + format.replace(/[\d,?\.?]+/, fnum);
326         },
327
328         /**
329          * Returns a number rendering function that can be reused to apply a number format multiple times efficiently
330          * @param {String} format Any valid number format string for {@link #number}
331          * @return {Function} The number formatting function
332          */
333         numberRenderer : function(format){
334             return function(v){
335                 return Ext.util.Format.number(v, format);
336             };
337         },
338
339         /**
340          * Selectively do a plural form of a word based on a numeric value. For example, in a template,
341          * {commentCount:plural("Comment")}  would result in "1 Comment" if commentCount was 1 or would be "x Comments"
342          * if the value is 0 or greater than 1.
343          * @param {Number} value The value to compare against
344          * @param {String} singular The singular form of the word
345          * @param {String} plural (optional) The plural form of the word (defaults to the singular with an "s")
346          */
347         plural : function(v, s, p){
348             return v +' ' + (v == 1 ? s : (p ? p : s+'s'));
349         },
350
351         /**
352          * Converts newline characters to the HTML tag &lt;br/>
353          * @param {String} The string value to format.
354          * @return {String} The string with embedded &lt;br/> tags in place of newlines.
355          */
356         nl2br : function(v){
357             return Ext.isEmpty(v) ? '' : v.replace(nl2brRe, '<br/>');
358         }
359     }
360 }();