1 <!DOCTYPE html><html><head><title>Sencha Documentation Project</title><link rel="stylesheet" href="../reset.css" type="text/css"><link rel="stylesheet" href="../prettify.css" type="text/css"><link rel="stylesheet" href="../prettify_sa.css" type="text/css"><script type="text/javascript" src="../prettify.js"></script></head><body onload="prettyPrint()"><pre class="prettyprint"><pre><span id='Ext-util.Format'>/**
2 </span> * @class Ext.util.Format
4 This class is a centralized place for formatting functions inside the library. It includes
5 functions to format various different types of data, such as text, dates and numeric values.
8 This class contains several options for localization. These can be set once the library has loaded,
9 all calls to the functions from that point will use the locale settings that were specified.
16 This class also uses the default date format defined here: {@link Ext.date#defaultFormat}.
18 __Using with renderers__
19 There are two helper functions that return a new function that can be used in conjunction with
24 renderer: Ext.util.Format.dateRenderer('Y-m-d')
27 renderer: Ext.util.Format.numberRenderer('0.000')
30 Functions that only take a single argument can also be passed directly:
33 renderer: Ext.util.Format.usMoney
35 dataIndex: 'productCode',
36 renderer: Ext.util.Format.uppercase
39 __Using with XTemplates__
40 XTemplates can also directly use Ext.util.Format functions:
43 'Date: {startDate:date("Y-m-d")}',
44 'Cost: {cost:usMoney}'
54 var UtilFormat = Ext.util.Format,
55 stripTagsRE = /<\/?[^>]+>/gi,
56 stripScriptsRe = /(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/ig,
59 // A RegExp to remove from a number format string, all characters except digits and '.'
60 formatCleanRe = /[^\d\.]/g,
62 // A RegExp to remove from a number format string, all characters except digits and the local decimal separator.
63 // Created on first use. The local decimal separator character must be initialized for this to be created.
66 Ext.apply(UtilFormat, {
67 <span id='Ext-util.Format-property-thousandSeparator'> /**
68 </span> * @type String
69 * @property thousandSeparator
70 * <p>The character that the {@link #number} function uses as a thousand separator.</p>
71 * <p>This defaults to <code>,</code>, but may be overridden in a locale file.</p>
73 thousandSeparator: ',',
75 <span id='Ext-util.Format-property-decimalSeparator'> /**
76 </span> * @type String
77 * @property decimalSeparator
78 * <p>The character that the {@link #number} function uses as a decimal point.</p>
79 * <p>This defaults to <code>.</code>, but may be overridden in a locale file.</p>
81 decimalSeparator: '.',
83 <span id='Ext-util.Format-property-currencyPrecision'> /**
84 </span> * @type Number
85 * @property currencyPrecision
86 * <p>The number of decimal places that the {@link #currency} function displays.</p>
87 * <p>This defaults to <code>2</code>, but may be overridden in a locale file.</p>
91 <span id='Ext-util.Format-property-currencySign'> /**
92 </span> * @type String
93 * @property currencySign
94 * <p>The currency sign that the {@link #currency} function displays.</p>
95 * <p>This defaults to <code>$</code>, but may be overridden in a locale file.</p>
99 <span id='Ext-util.Format-property-currencyAtEnd'> /**
100 </span> * @type Boolean
101 * @property currencyAtEnd
102 * <p>This may be set to <code>true</code> to make the {@link #currency} function
103 * append the currency sign to the formatted value.</p>
104 * <p>This defaults to <code>false</code>, but may be overridden in a locale file.</p>
106 currencyAtEnd: false,
108 <span id='Ext-util.Format-method-undef'> /**
109 </span> * Checks a reference and converts it to empty string if it is undefined
110 * @param {Mixed} value Reference to check
111 * @return {Mixed} Empty string if converted, otherwise the original value
113 undef : function(value) {
114 return value !== undefined ? value : "";
117 <span id='Ext-util.Format-method-defaultValue'> /**
118 </span> * Checks a reference and converts it to the default value if it's empty
119 * @param {Mixed} value Reference to check
120 * @param {String} defaultValue The value to insert of it's undefined (defaults to "")
123 defaultValue : function(value, defaultValue) {
124 return value !== undefined && value !== '' ? value : defaultValue;
127 <span id='Ext-util.Format-method-substr'> /**
128 </span> * Returns a substring from within an original string
129 * @param {String} value The original text
130 * @param {Number} start The start index of the substring
131 * @param {Number} length The length of the substring
132 * @return {String} The substring
134 substr : function(value, start, length) {
135 return String(value).substr(start, length);
138 <span id='Ext-util.Format-method-lowercase'> /**
139 </span> * Converts a string to all lower case letters
140 * @param {String} value The text to convert
141 * @return {String} The converted text
143 lowercase : function(value) {
144 return String(value).toLowerCase();
147 <span id='Ext-util.Format-method-uppercase'> /**
148 </span> * Converts a string to all upper case letters
149 * @param {String} value The text to convert
150 * @return {String} The converted text
152 uppercase : function(value) {
153 return String(value).toUpperCase();
156 <span id='Ext-util.Format-method-usMoney'> /**
157 </span> * Format a number as US currency
158 * @param {Number/String} value The numeric value to format
159 * @return {String} The formatted currency string
161 usMoney : function(v) {
162 return UtilFormat.currency(v, '$', 2);
165 <span id='Ext-util.Format-method-currency'> /**
166 </span> * Format a number as a currency
167 * @param {Number/String} value The numeric value to format
168 * @param {String} sign The currency sign to use (defaults to {@link #currencySign})
169 * @param {Number} decimals The number of decimals to use for the currency (defaults to {@link #currencyPrecision})
170 * @param {Boolean} end True if the currency sign should be at the end of the string (defaults to {@link #currencyAtEnd})
171 * @return {String} The formatted currency string
173 currency: function(v, currencySign, decimals, end) {
174 var negativeSign = '',
175 format = ",0",
182 decimals = decimals || UtilFormat.currencyPrecision;
183 format += format + (decimals > 0 ? '.' : '');
184 for (; i < decimals; i++) {
187 v = UtilFormat.number(v, format);
188 if ((end || UtilFormat.currencyAtEnd) === true) {
189 return Ext.String.format("{0}{1}{2}", negativeSign, v, currencySign || UtilFormat.currencySign);
191 return Ext.String.format("{0}{1}{2}", negativeSign, currencySign || UtilFormat.currencySign, v);
195 <span id='Ext-util.Format-method-date'> /**
196 </span> * Formats the passed date using the specified format pattern.
197 * @param {String/Date} value The value to format. If a string is passed, it is converted to a Date by the Javascript
198 * Date object's <a href="http://www.w3schools.com/jsref/jsref_parse.asp">parse()</a> method.
199 * @param {String} format (Optional) Any valid date format string. Defaults to {@link Ext.Date#defaultFormat}.
200 * @return {String} The formatted date string.
202 date: function(v, format) {
206 if (!Ext.isDate(v)) {
207 v = new Date(Date.parse(v));
209 return Ext.Date.dateFormat(v, format || Ext.Date.defaultFormat);
212 <span id='Ext-util.Format-method-dateRenderer'> /**
213 </span> * Returns a date rendering function that can be reused to apply a date format multiple times efficiently
214 * @param {String} format Any valid date format string. Defaults to {@link Ext.Date#defaultFormat}.
215 * @return {Function} The date formatting function
217 dateRenderer : function(format) {
219 return UtilFormat.date(v, format);
223 <span id='Ext-util.Format-method-stripTags'> /**
224 </span> * Strips all HTML tags
225 * @param {Mixed} value The text from which to strip tags
226 * @return {String} The stripped text
228 stripTags : function(v) {
229 return !v ? v : String(v).replace(stripTagsRE, "");
232 <span id='Ext-util.Format-method-stripScripts'> /**
233 </span> * Strips all script tags
234 * @param {Mixed} value The text from which to strip script tags
235 * @return {String} The stripped text
237 stripScripts : function(v) {
238 return !v ? v : String(v).replace(stripScriptsRe, "");
241 <span id='Ext-util.Format-method-fileSize'> /**
242 </span> * Simple format for a file size (xxx bytes, xxx KB, xxx MB)
243 * @param {Number/String} size The numeric value to format
244 * @return {String} The formatted file size
246 fileSize : function(size) {
247 if (size < 1024) {
248 return size + " bytes";
249 } else if (size < 1048576) {
250 return (Math.round(((size*10) / 1024))/10) + " KB";
252 return (Math.round(((size*10) / 1048576))/10) + " MB";
256 <span id='Ext-util.Format-method-math'> /**
257 </span> * It does simple math for use in a template, for example:<pre><code>
258 * var tpl = new Ext.Template('{value} * 10 = {value:math("* 10")}');
259 * </code></pre>
260 * @return {Function} A function that operates on the passed value.
265 return function(v, a){
267 fns[a] = Ext.functionFactory('v', 'return v ' + a + ';');
273 <span id='Ext-util.Format-method-round'> /**
274 </span> * Rounds the passed number to the required decimal precision.
275 * @param {Number/String} value The numeric value to round.
276 * @param {Number} precision The number of decimal places to which to round the first parameter's value.
277 * @return {Number} The rounded value.
279 round : function(value, precision) {
280 var result = Number(value);
281 if (typeof precision == 'number') {
282 precision = Math.pow(10, precision);
283 result = Math.round(value * precision) / precision;
288 <span id='Ext-util.Format-method-number'> /**
289 </span> * <p>Formats the passed number according to the passed format string.</p>
290 * <p>The number of digits after the decimal separator character specifies the number of
291 * decimal places in the resulting string. The <u>local-specific</u> decimal character is used in the result.</p>
292 * <p>The <i>presence</i> of a thousand separator character in the format string specifies that
293 * the <u>locale-specific</u> thousand separator (if any) is inserted separating thousand groups.</p>
294 * <p>By default, "," is expected as the thousand separator, and "." is expected as the decimal separator.</p>
295 * <p><b>New to Ext4</b></p>
296 * <p>Locale-specific characters are always used in the formatted output when inserting
297 * thousand and decimal separators.</p>
298 * <p>The format string must specify separator characters according to US/UK conventions ("," as the
299 * thousand separator, and "." as the decimal separator)</p>
300 * <p>To allow specification of format strings according to local conventions for separator characters, add
301 * the string <code>/i</code> to the end of the format string.</p>
302 * <div style="margin-left:40px">examples (123456.789):
303 * <div style="margin-left:10px">
304 * 0 - (123456) show only digits, no precision<br>
305 * 0.00 - (123456.78) show only digits, 2 precision<br>
306 * 0.0000 - (123456.7890) show only digits, 4 precision<br>
307 * 0,000 - (123,456) show comma and digits, no precision<br>
308 * 0,000.00 - (123,456.78) show comma and digits, 2 precision<br>
309 * 0,0.00 - (123,456.78) shortcut method, show comma and digits, 2 precision<br>
310 * To allow specification of the formatting string using UK/US grouping characters (,) and decimal (.) for international numbers, add /i to the end.
311 * For example: 0.000,00/i
312 * </div></div>
313 * @param {Number} v The number to format.
314 * @param {String} format The way you would like to format this text.
315 * @return {String} The formatted number.
318 function(v, formatString) {
322 v = Ext.Number.from(v, NaN);
326 var comma = UtilFormat.thousandSeparator,
327 dec = UtilFormat.decimalSeparator,
335 // The "/i" suffix allows caller to use a locale-specific formatting string.
336 // Clean the format string by removing all but numerals and the decimal separator.
337 // Then split the format string into pre and post decimal segments according to *what* the
338 // decimal separator is. If they are specifying "/i", they are using the local convention in the format string.
339 if (formatString.substr(formatString.length - 2) == '/i') {
340 if (!I18NFormatCleanRe) {
341 I18NFormatCleanRe = new RegExp('[^\\d\\' + UtilFormat.decimalSeparator + ']','g');
343 formatString = formatString.substr(0, formatString.length - 2);
345 hasComma = formatString.indexOf(comma) != -1;
346 psplit = formatString.replace(I18NFormatCleanRe, '').split(dec);
348 hasComma = formatString.indexOf(',') != -1;
349 psplit = formatString.replace(formatCleanRe, '').split('.');
352 if (1 < psplit.length) {
353 v = v.toFixed(psplit[1].length);
354 } else if(2 < psplit.length) {
357 sourceClass: "Ext.util.Format",
358 sourceMethod: "number",
360 formatString: formatString,
361 msg: "Invalid number format, should have no more than 1 decimal"
368 var fnum = v.toString();
370 psplit = fnum.split('.');
373 var cnum = psplit[0],
376 m = Math.floor(j / 3),
377 n = cnum.length % 3 || 3,
380 for (i = 0; i < j; i += n) {
385 parr[parr.length] = cnum.substr(i, n);
388 fnum = parr.join(comma);
390 fnum += dec + psplit[1];
394 fnum = psplit[0] + dec + psplit[1];
398 return (neg ? '-' : '') + formatString.replace(/[\d,?\.?]+/, fnum);
401 <span id='Ext-util.Format-method-numberRenderer'> /**
402 </span> * Returns a number rendering function that can be reused to apply a number format multiple times efficiently
403 * @param {String} format Any valid number format string for {@link #number}
404 * @return {Function} The number formatting function
406 numberRenderer : function(format) {
408 return UtilFormat.number(v, format);
412 <span id='Ext-util.Format-method-plural'> /**
413 </span> * Selectively do a plural form of a word based on a numeric value. For example, in a template,
414 * {commentCount:plural("Comment")} would result in "1 Comment" if commentCount was 1 or would be "x Comments"
415 * if the value is 0 or greater than 1.
416 * @param {Number} value The value to compare against
417 * @param {String} singular The singular form of the word
418 * @param {String} plural (optional) The plural form of the word (defaults to the singular with an "s")
420 plural : function(v, s, p) {
421 return v +' ' + (v == 1 ? s : (p ? p : s+'s'));
424 <span id='Ext-util.Format-method-nl2br'> /**
425 </span> * Converts newline characters to the HTML tag &lt;br/>
426 * @param {String} The string value to format.
427 * @return {String} The string with embedded &lt;br/> tags in place of newlines.
429 nl2br : function(v) {
430 return Ext.isEmpty(v) ? '' : v.replace(nl2brRe, '<br/>');
433 <span id='Ext-util.Format-property-capitalize'> /**
434 </span> * Capitalize the given string. See {@link Ext.String#capitalize}.
436 capitalize: Ext.String.capitalize,
438 <span id='Ext-util.Format-property-ellipsis'> /**
439 </span> * Truncate a string and add an ellipsis ('...') to the end if it exceeds the specified length.
440 * See {@link Ext.String#ellipsis}.
442 ellipsis: Ext.String.ellipsis,
444 <span id='Ext-util.Format-property-format'> /**
445 </span> * Formats to a string. See {@link Ext.String#format}
447 format: Ext.String.format,
449 <span id='Ext-util.Format-property-htmlDecode'> /**
450 </span> * Convert certain characters (&, <, >, and ') from their HTML character equivalents.
451 * See {@link Ext.string#htmlDecode}.
453 htmlDecode: Ext.String.htmlDecode,
455 <span id='Ext-util.Format-property-htmlEncode'> /**
456 </span> * Convert certain characters (&, <, >, and ') to their HTML character equivalents for literal display in web pages.
457 * See {@link Ext.String#htmlEncode}.
459 htmlEncode: Ext.String.htmlEncode,
461 <span id='Ext-util.Format-property-leftPad'> /**
462 </span> * Adds left padding to a string. See {@link Ext.String#leftPad}
464 leftPad: Ext.String.leftPad,
466 <span id='Ext-util.Format-property-trim'> /**
467 </span> * Trims any whitespace from either side of a string. See {@link Ext.String#trim}.
469 trim : Ext.String.trim,
471 <span id='Ext-util.Format-method-parseBox'> /**
472 </span> * Parses a number or string representing margin sizes into an object. Supports CSS-style margin declarations
473 * (e.g. 10, "10", "10 10", "10 10 10" and "10 10 10 10" are all valid options and would return the same result)
474 * @param {Number|String} v The encoded margins
475 * @return {Object} An object with margin sizes for top, right, bottom and left
477 parseBox : function(box) {
478 if (Ext.isNumber(box)) {
479 box = box.toString();
481 var parts = box.split(' '),
485 parts[1] = parts[2] = parts[3] = parts[0];
496 top :parseInt(parts[0], 10) || 0,
497 right :parseInt(parts[1], 10) || 0,
498 bottom:parseInt(parts[2], 10) || 0,
499 left :parseInt(parts[3], 10) || 0
503 <span id='Ext-util.Format-method-escapeRegex'> /**
504 </span> * Escapes the passed string for use in a regular expression
505 * @param {String} str
508 escapeRegex : function(s) {
509 return s.replace(/([\-.*+?\^${}()|\[\]\/\\])/g, "\\$1");
513 </pre></pre></body></html>