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