3 * Copyright(c) 2006-2010 Sencha Inc.
5 * http://www.sencha.com/license
8 * @class Ext.util.Format
9 * Reusable data formatting functions
12 Ext.util.Format = function() {
13 var trimRe = /^\s+|\s+$/g,
14 stripTagsRE = /<\/?[^>]+>/gi,
15 stripScriptsRe = /(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/ig,
20 * Truncate a string and add an ellipsis ('...') to the end if it exceeds the specified length
21 * @param {String} value The string to truncate
22 * @param {Number} length The maximum length to allow before truncating
23 * @param {Boolean} word True to try to find a common work break
24 * @return {String} The converted text
26 ellipsis : function(value, len, word) {
27 if (value && value.length > len) {
29 var vs = value.substr(0, len - 2),
30 index = Math.max(vs.lastIndexOf(' '), vs.lastIndexOf('.'), vs.lastIndexOf('!'), vs.lastIndexOf('?'));
31 if (index == -1 || index < (len - 15)) {
32 return value.substr(0, len - 3) + "...";
34 return vs.substr(0, index) + "...";
37 return value.substr(0, len - 3) + "...";
44 * Checks a reference and converts it to empty string if it is undefined
45 * @param {Mixed} value Reference to check
46 * @return {Mixed} Empty string if converted, otherwise the original value
48 undef : function(value) {
49 return value !== undefined ? value : "";
53 * Checks a reference and converts it to the default value if it's empty
54 * @param {Mixed} value Reference to check
55 * @param {String} defaultValue The value to insert of it's undefined (defaults to "")
58 defaultValue : function(value, defaultValue) {
59 return value !== undefined && value !== '' ? value : defaultValue;
63 * Convert certain characters (&, <, >, and ') to their HTML character equivalents for literal display in web pages.
64 * @param {String} value The string to encode
65 * @return {String} The encoded text
67 htmlEncode : function(value) {
68 return !value ? value : String(value).replace(/&/g, "&").replace(/>/g, ">").replace(/</g, "<").replace(/"/g, """);
72 * Convert certain characters (&, <, >, and ') from their HTML character equivalents.
73 * @param {String} value The string to decode
74 * @return {String} The decoded text
76 htmlDecode : function(value) {
77 return !value ? value : String(value).replace(/>/g, ">").replace(/</g, "<").replace(/"/g, '"').replace(/&/g, "&");
81 * Trims any whitespace from either side of a string
82 * @param {String} value The text to trim
83 * @return {String} The trimmed text
85 trim : function(value) {
86 return String(value).replace(trimRe, "");
90 * Returns a substring from within an original string
91 * @param {String} value The original text
92 * @param {Number} start The start index of the substring
93 * @param {Number} length The length of the substring
94 * @return {String} The substring
96 substr : function(value, start, length) {
97 return String(value).substr(start, length);
101 * Converts a string to all lower case letters
102 * @param {String} value The text to convert
103 * @return {String} The converted text
105 lowercase : function(value) {
106 return String(value).toLowerCase();
110 * Converts a string to all upper case letters
111 * @param {String} value The text to convert
112 * @return {String} The converted text
114 uppercase : function(value) {
115 return String(value).toUpperCase();
119 * Converts the first character only of a string to upper case
120 * @param {String} value The text to convert
121 * @return {String} The converted text
123 capitalize : function(value) {
124 return !value ? value : value.charAt(0).toUpperCase() + value.substr(1).toLowerCase();
128 call : function(value, fn) {
129 if (arguments.length > 2) {
130 var args = Array.prototype.slice.call(arguments, 2);
132 return eval(fn).apply(window, args);
134 return eval(fn).call(window, value);
139 * Format a number as US currency
140 * @param {Number/String} value The numeric value to format
141 * @return {String} The formatted currency string
143 usMoney : function(v) {
144 v = (Math.round((v-0)*100))/100;
145 v = (v == Math.floor(v)) ? v + ".00" : ((v*10 == Math.floor(v*10)) ? v + "0" : v);
147 var ps = v.split('.'),
149 sub = ps[1] ? '.'+ ps[1] : '.00',
151 while (r.test(whole)) {
152 whole = whole.replace(r, '$1' + ',' + '$2');
155 if (v.charAt(0) == '-') {
156 return '-$' + v.substr(1);
162 * Parse a value into a formatted date using the specified format pattern.
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)
164 * @param {String} format (optional) Any valid date format string (defaults to 'm/d/Y')
165 * @return {String} The formatted date string
167 date : function(v, format) {
171 if (!Ext.isDate(v)) {
172 v = new Date(Date.parse(v));
174 return v.dateFormat(format || "m/d/Y");
178 * Returns a date rendering function that can be reused to apply a date format multiple times efficiently
179 * @param {String} format Any valid date format string
180 * @return {Function} The date formatting function
182 dateRenderer : function(format) {
184 return Ext.util.Format.date(v, format);
189 * Strips all HTML tags
190 * @param {Mixed} value The text from which to strip tags
191 * @return {String} The stripped text
193 stripTags : function(v) {
194 return !v ? v : String(v).replace(stripTagsRE, "");
198 * Strips all script tags
199 * @param {Mixed} value The text from which to strip script tags
200 * @return {String} The stripped text
202 stripScripts : function(v) {
203 return !v ? v : String(v).replace(stripScriptsRe, "");
207 * Simple format for a file size (xxx bytes, xxx KB, xxx MB)
208 * @param {Number/String} size The numeric value to format
209 * @return {String} The formatted file size
211 fileSize : function(size) {
213 return size + " bytes";
214 } else if (size < 1048576) {
215 return (Math.round(((size*10) / 1024))/10) + " KB";
217 return (Math.round(((size*10) / 1048576))/10) + " MB";
222 * It does simple math for use in a template, for example:<pre><code>
223 * var tpl = new Ext.Template('{value} * 10 = {value:math("* 10")}');
225 * @return {Function} A function that operates on the passed value.
230 return function(v, a){
232 fns[a] = new Function('v', 'return v ' + a + ';');
239 * Rounds the passed number to the required decimal precision.
240 * @param {Number/String} value The numeric value to round.
241 * @param {Number} precision The number of decimal places to which to round the first parameter's value.
242 * @return {Number} The rounded value.
244 round : function(value, precision) {
245 var result = Number(value);
246 if (typeof precision == 'number') {
247 precision = Math.pow(10, precision);
248 result = Math.round(value * precision) / precision;
254 * Formats the number according to the format string.
255 * <div style="margin-left:40px">examples (123456.789):
256 * <div style="margin-left:10px">
257 * 0 - (123456) show only digits, no precision<br>
258 * 0.00 - (123456.78) show only digits, 2 precision<br>
259 * 0.0000 - (123456.7890) show only digits, 4 precision<br>
260 * 0,000 - (123,456) show comma and digits, no precision<br>
261 * 0,000.00 - (123,456.78) show comma and digits, 2 precision<br>
262 * 0,0.00 - (123,456.78) shortcut method, show comma and digits, 2 precision<br>
263 * To reverse the grouping (,) and decimal (.) for international numbers, add /i to the end.
264 * For example: 0.000,00/i
266 * @param {Number} v The number to format.
267 * @param {String} format The way you would like to format this text.
268 * @return {String} The formatted number.
270 number: function(v, format) {
284 if (format.substr(format.length - 2) == '/i') {
285 format = format.substr(0, format.length - 2);
291 var hasComma = format.indexOf(comma) != -1,
292 psplit = (i18n ? format.replace(/[^\d\,]/g, '') : format.replace(/[^\d\.]/g, '')).split(dec);
294 if (1 < psplit.length) {
295 v = v.toFixed(psplit[1].length);
296 } else if(2 < psplit.length) {
297 throw ('NumberFormatException: invalid format, formats should have no more than 1 period: ' + format);
302 var fnum = v.toString();
304 psplit = fnum.split('.');
307 var cnum = psplit[0],
310 m = Math.floor(j / 3),
311 n = cnum.length % 3 || 3,
314 for (i = 0; i < j; i += n) {
319 parr[parr.length] = cnum.substr(i, n);
322 fnum = parr.join(comma);
324 fnum += dec + psplit[1];
328 fnum = psplit[0] + dec + psplit[1];
332 return (neg ? '-' : '') + format.replace(/[\d,?\.?]+/, fnum);
336 * Returns a number rendering function that can be reused to apply a number format multiple times efficiently
337 * @param {String} format Any valid number format string for {@link #number}
338 * @return {Function} The number formatting function
340 numberRenderer : function(format) {
342 return Ext.util.Format.number(v, format);
347 * Selectively do a plural form of a word based on a numeric value. For example, in a template,
348 * {commentCount:plural("Comment")} would result in "1 Comment" if commentCount was 1 or would be "x Comments"
349 * if the value is 0 or greater than 1.
350 * @param {Number} value The value to compare against
351 * @param {String} singular The singular form of the word
352 * @param {String} plural (optional) The plural form of the word (defaults to the singular with an "s")
354 plural : function(v, s, p) {
355 return v +' ' + (v == 1 ? s : (p ? p : s+'s'));
359 * Converts newline characters to the HTML tag <br/>
360 * @param {String} The string value to format.
361 * @return {String} The string with embedded <br/> tags in place of newlines.
363 nl2br : function(v) {
364 return Ext.isEmpty(v) ? '' : v.replace(nl2brRe, '<br/>');