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