commit extjs-2.2.1
[extjs.git] / source / util / Format.js
1 /*\r
2  * Ext JS Library 2.2.1\r
3  * Copyright(c) 2006-2009, Ext JS, LLC.\r
4  * licensing@extjs.com\r
5  * \r
6  * http://extjs.com/license\r
7  */\r
8 \r
9 /**\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     return {\r
17         /**\r
18          * Truncate a string and add an ellipsis ('...') to the end if it exceeds the specified length\r
19          * @param {String} value The string to truncate\r
20          * @param {Number} length The maximum length to allow before truncating\r
21          * @return {String} The converted text\r
22          */\r
23         ellipsis : function(value, len){\r
24             if(value && value.length > len){\r
25                 return value.substr(0, len-3)+"...";\r
26             }\r
27             return value;\r
28         },\r
29 \r
30         /**\r
31          * Checks a reference and converts it to empty string if it is undefined\r
32          * @param {Mixed} value Reference to check\r
33          * @return {Mixed} Empty string if converted, otherwise the original value\r
34          */\r
35         undef : function(value){\r
36             return value !== undefined ? value : "";\r
37         },\r
38 \r
39         /**\r
40          * Checks a reference and converts it to the default value if it's empty\r
41          * @param {Mixed} value Reference to check\r
42          * @param {String} defaultValue The value to insert of it's undefined (defaults to "")\r
43          * @return {String}\r
44          */\r
45         defaultValue : function(value, defaultValue){\r
46             return value !== undefined && value !== '' ? value : defaultValue;\r
47         },\r
48 \r
49         /**\r
50          * Convert certain characters (&, <, >, and ') to their HTML character equivalents for literal display in web pages.\r
51          * @param {String} value The string to encode\r
52          * @return {String} The encoded text\r
53          */\r
54         htmlEncode : function(value){\r
55             return !value ? value : String(value).replace(/&/g, "&amp;").replace(/>/g, "&gt;").replace(/</g, "&lt;").replace(/"/g, "&quot;");\r
56         },\r
57 \r
58         /**\r
59          * Convert certain characters (&, <, >, and ') from their HTML character equivalents.\r
60          * @param {String} value The string to decode\r
61          * @return {String} The decoded text\r
62          */\r
63         htmlDecode : function(value){\r
64             return !value ? value : String(value).replace(/&gt;/g, ">").replace(/&lt;/g, "<").replace(/&quot;/g, '"').replace(/&amp;/g, "&");\r
65         },\r
66 \r
67         /**\r
68          * Trims any whitespace from either side of a string\r
69          * @param {String} value The text to trim\r
70          * @return {String} The trimmed text\r
71          */\r
72         trim : function(value){\r
73             return String(value).replace(trimRe, "");\r
74         },\r
75 \r
76         /**\r
77          * Returns a substring from within an original string\r
78          * @param {String} value The original text\r
79          * @param {Number} start The start index of the substring\r
80          * @param {Number} length The length of the substring\r
81          * @return {String} The substring\r
82          */\r
83         substr : function(value, start, length){\r
84             return String(value).substr(start, length);\r
85         },\r
86 \r
87         /**\r
88          * Converts a string to all lower case letters\r
89          * @param {String} value The text to convert\r
90          * @return {String} The converted text\r
91          */\r
92         lowercase : function(value){\r
93             return String(value).toLowerCase();\r
94         },\r
95 \r
96         /**\r
97          * Converts a string to all upper case letters\r
98          * @param {String} value The text to convert\r
99          * @return {String} The converted text\r
100          */\r
101         uppercase : function(value){\r
102             return String(value).toUpperCase();\r
103         },\r
104 \r
105         /**\r
106          * Converts the first character only of a string to upper case\r
107          * @param {String} value The text to convert\r
108          * @return {String} The converted text\r
109          */\r
110         capitalize : function(value){\r
111             return !value ? value : value.charAt(0).toUpperCase() + value.substr(1).toLowerCase();\r
112         },\r
113 \r
114         // private\r
115         call : function(value, fn){\r
116             if(arguments.length > 2){\r
117                 var args = Array.prototype.slice.call(arguments, 2);\r
118                 args.unshift(value);\r
119                 return eval(fn).apply(window, args);\r
120             }else{\r
121                 return eval(fn).call(window, value);\r
122             }\r
123         },\r
124 \r
125         /**\r
126          * Format a number as US currency\r
127          * @param {Number/String} value The numeric value to format\r
128          * @return {String} The formatted currency string\r
129          */\r
130         usMoney : function(v){\r
131             v = (Math.round((v-0)*100))/100;\r
132             v = (v == Math.floor(v)) ? v + ".00" : ((v*10 == Math.floor(v*10)) ? v + "0" : v);\r
133             v = String(v);\r
134             var ps = v.split('.');\r
135             var whole = ps[0];\r
136             var sub = ps[1] ? '.'+ ps[1] : '.00';\r
137             var r = /(\d+)(\d{3})/;\r
138             while (r.test(whole)) {\r
139                 whole = whole.replace(r, '$1' + ',' + '$2');\r
140             }\r
141             v = whole + sub;\r
142             if(v.charAt(0) == '-'){\r
143                 return '-$' + v.substr(1);\r
144             }\r
145             return "$" +  v;\r
146         },\r
147 \r
148         /**\r
149          * Parse a value into a formatted date using the specified format pattern.\r
150          * @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
151          * @param {String} format (optional) Any valid date format string (defaults to 'm/d/Y')\r
152          * @return {String} The formatted date string\r
153          */\r
154         date : function(v, format){\r
155             if(!v){\r
156                 return "";\r
157             }\r
158             if(!Ext.isDate(v)){\r
159                 v = new Date(Date.parse(v));\r
160             }\r
161             return v.dateFormat(format || "m/d/Y");\r
162         },\r
163 \r
164         /**\r
165          * Returns a date rendering function that can be reused to apply a date format multiple times efficiently\r
166          * @param {String} format Any valid date format string\r
167          * @return {Function} The date formatting function\r
168          */\r
169         dateRenderer : function(format){\r
170             return function(v){\r
171                 return Ext.util.Format.date(v, format);\r
172             };\r
173         },\r
174 \r
175         // private\r
176         stripTagsRE : /<\/?[^>]+>/gi,\r
177         \r
178         /**\r
179          * Strips all HTML tags\r
180          * @param {Mixed} value The text from which to strip tags\r
181          * @return {String} The stripped text\r
182          */\r
183         stripTags : function(v){\r
184             return !v ? v : String(v).replace(this.stripTagsRE, "");\r
185         },\r
186 \r
187         // private\r
188         stripScriptsRe : /(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/ig,\r
189 \r
190         /**\r
191          * Strips all script tags\r
192          * @param {Mixed} value The text from which to strip script tags\r
193          * @return {String} The stripped text\r
194          */\r
195         stripScripts : function(v){\r
196             return !v ? v : String(v).replace(this.stripScriptsRe, "");\r
197         },\r
198 \r
199         /**\r
200          * Simple format for a file size (xxx bytes, xxx KB, xxx MB)\r
201          * @param {Number/String} size The numeric value to format\r
202          * @return {String} The formatted file size\r
203          */\r
204         fileSize : function(size){\r
205             if(size < 1024) {\r
206                 return size + " bytes";\r
207             } else if(size < 1048576) {\r
208                 return (Math.round(((size*10) / 1024))/10) + " KB";\r
209             } else {\r
210                 return (Math.round(((size*10) / 1048576))/10) + " MB";\r
211             }\r
212         },\r
213 \r
214         math : function(){\r
215             var fns = {};\r
216             return function(v, a){\r
217                 if(!fns[a]){\r
218                     fns[a] = new Function('v', 'return v ' + a + ';');\r
219                 }\r
220                 return fns[a](v);\r
221             }\r
222         }(),\r
223 \r
224                 /**\r
225                  * Converts newline characters to the HTML tag &lt;br/>\r
226                  * @param {String} The string value to format.\r
227          * @return {String} The string with embedded &lt;br/> tags in place of newlines.\r
228                  */\r
229         nl2br : function(v){\r
230             return v === undefined || v === null ? '' : v.replace(/\n/g, '<br/>');\r
231         }\r
232     };\r
233 }();