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