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