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