4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
5 <title>The source code</title>
6 <link href="../prettify/prettify.css" type="text/css" rel="stylesheet" />
7 <script type="text/javascript" src="../prettify/prettify.js"></script>
8 <style type="text/css">
9 .highlight { display: block; background-color: #ddd; }
11 <script type="text/javascript">
12 function highlight() {
13 document.getElementById(location.hash.replace(/#/, "")).className = "highlight";
17 <body onload="prettyPrint(); highlight();">
18 <pre class="prettyprint lang-js"><span id='Ext-util-Format'>/**
19 </span> * @class Ext.util.Format
21 This class is a centralized place for formatting functions inside the library. It includes
22 functions to format various different types of data, such as text, dates and numeric values.
25 This class contains several options for localization. These can be set once the library has loaded,
26 all calls to the functions from that point will use the locale settings that were specified.
33 This class also uses the default date format defined here: {@link Ext.Date#defaultFormat}.
35 __Using with renderers__
36 There are two helper functions that return a new function that can be used in conjunction with
41 renderer: Ext.util.Format.dateRenderer('Y-m-d')
44 renderer: Ext.util.Format.numberRenderer('0.000')
47 Functions that only take a single argument can also be passed directly:
50 renderer: Ext.util.Format.usMoney
52 dataIndex: 'productCode',
53 renderer: Ext.util.Format.uppercase
56 __Using with XTemplates__
57 XTemplates can also directly use Ext.util.Format functions:
60 'Date: {startDate:date("Y-m-d")}',
61 'Cost: {cost:usMoney}'
71 var UtilFormat = Ext.util.Format,
72 stripTagsRE = /<\/?[^>]+>/gi,
73 stripScriptsRe = /(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/ig,
76 // A RegExp to remove from a number format string, all characters except digits and '.'
77 formatCleanRe = /[^\d\.]/g,
79 // A RegExp to remove from a number format string, all characters except digits and the local decimal separator.
80 // Created on first use. The local decimal separator character must be initialized for this to be created.
83 Ext.apply(UtilFormat, {
84 <span id='Ext-util-Format-property-thousandSeparator'> /**
85 </span> * @type String
86 * @property thousandSeparator
87 * <p>The character that the {@link #number} function uses as a thousand separator.</p>
88 * <p>This defaults to <code>,</code>, but may be overridden in a locale file.</p>
90 thousandSeparator: ',',
92 <span id='Ext-util-Format-property-decimalSeparator'> /**
93 </span> * @type String
94 * @property decimalSeparator
95 * <p>The character that the {@link #number} function uses as a decimal point.</p>
96 * <p>This defaults to <code>.</code>, but may be overridden in a locale file.</p>
98 decimalSeparator: '.',
100 <span id='Ext-util-Format-property-currencyPrecision'> /**
101 </span> * @type Number
102 * @property currencyPrecision
103 * <p>The number of decimal places that the {@link #currency} function displays.</p>
104 * <p>This defaults to <code>2</code>, but may be overridden in a locale file.</p>
106 currencyPrecision: 2,
108 <span id='Ext-util-Format-property-currencySign'> /**
109 </span> * @type String
110 * @property currencySign
111 * <p>The currency sign that the {@link #currency} function displays.</p>
112 * <p>This defaults to <code>$</code>, but may be overridden in a locale file.</p>
116 <span id='Ext-util-Format-property-currencyAtEnd'> /**
117 </span> * @type Boolean
118 * @property currencyAtEnd
119 * <p>This may be set to <code>true</code> to make the {@link #currency} function
120 * append the currency sign to the formatted value.</p>
121 * <p>This defaults to <code>false</code>, but may be overridden in a locale file.</p>
123 currencyAtEnd: false,
125 <span id='Ext-util-Format-method-undef'> /**
126 </span> * Checks a reference and converts it to empty string if it is undefined
127 * @param {Mixed} value Reference to check
128 * @return {Mixed} Empty string if converted, otherwise the original value
130 undef : function(value) {
131 return value !== undefined ? value : "";
134 <span id='Ext-util-Format-method-defaultValue'> /**
135 </span> * Checks a reference and converts it to the default value if it's empty
136 * @param {Mixed} value Reference to check
137 * @param {String} defaultValue The value to insert of it's undefined (defaults to "")
140 defaultValue : function(value, defaultValue) {
141 return value !== undefined && value !== '' ? value : defaultValue;
144 <span id='Ext-util-Format-method-substr'> /**
145 </span> * Returns a substring from within an original string
146 * @param {String} value The original text
147 * @param {Number} start The start index of the substring
148 * @param {Number} length The length of the substring
149 * @return {String} The substring
151 substr : function(value, start, length) {
152 return String(value).substr(start, length);
155 <span id='Ext-util-Format-method-lowercase'> /**
156 </span> * Converts a string to all lower case letters
157 * @param {String} value The text to convert
158 * @return {String} The converted text
160 lowercase : function(value) {
161 return String(value).toLowerCase();
164 <span id='Ext-util-Format-method-uppercase'> /**
165 </span> * Converts a string to all upper case letters
166 * @param {String} value The text to convert
167 * @return {String} The converted text
169 uppercase : function(value) {
170 return String(value).toUpperCase();
173 <span id='Ext-util-Format-method-usMoney'> /**
174 </span> * Format a number as US currency
175 * @param {Number/String} value The numeric value to format
176 * @return {String} The formatted currency string
178 usMoney : function(v) {
179 return UtilFormat.currency(v, '$', 2);
182 <span id='Ext-util-Format-method-currency'> /**
183 </span> * Format a number as a currency
184 * @param {Number/String} value The numeric value to format
185 * @param {String} sign The currency sign to use (defaults to {@link #currencySign})
186 * @param {Number} decimals The number of decimals to use for the currency (defaults to {@link #currencyPrecision})
187 * @param {Boolean} end True if the currency sign should be at the end of the string (defaults to {@link #currencyAtEnd})
188 * @return {String} The formatted currency string
190 currency: function(v, currencySign, decimals, end) {
191 var negativeSign = '',
192 format = ",0",
199 decimals = decimals || UtilFormat.currencyPrecision;
200 format += format + (decimals > 0 ? '.' : '');
201 for (; i < decimals; i++) {
204 v = UtilFormat.number(v, format);
205 if ((end || UtilFormat.currencyAtEnd) === true) {
206 return Ext.String.format("{0}{1}{2}", negativeSign, v, currencySign || UtilFormat.currencySign);
208 return Ext.String.format("{0}{1}{2}", negativeSign, currencySign || UtilFormat.currencySign, v);
212 <span id='Ext-util-Format-method-date'> /**
213 </span> * Formats the passed date using the specified format pattern.
214 * @param {String/Date} value The value to format. If a string is passed, it is converted to a Date by the Javascript
215 * Date object's <a href="http://www.w3schools.com/jsref/jsref_parse.asp">parse()</a> method.
216 * @param {String} format (Optional) Any valid date format string. Defaults to {@link Ext.Date#defaultFormat}.
217 * @return {String} The formatted date string.
219 date: function(v, format) {
223 if (!Ext.isDate(v)) {
224 v = new Date(Date.parse(v));
226 return Ext.Date.dateFormat(v, format || Ext.Date.defaultFormat);
229 <span id='Ext-util-Format-method-dateRenderer'> /**
230 </span> * Returns a date rendering function that can be reused to apply a date format multiple times efficiently
231 * @param {String} format Any valid date format string. Defaults to {@link Ext.Date#defaultFormat}.
232 * @return {Function} The date formatting function
234 dateRenderer : function(format) {
236 return UtilFormat.date(v, format);
240 <span id='Ext-util-Format-method-stripTags'> /**
241 </span> * Strips all HTML tags
242 * @param {Mixed} value The text from which to strip tags
243 * @return {String} The stripped text
245 stripTags : function(v) {
246 return !v ? v : String(v).replace(stripTagsRE, "");
249 <span id='Ext-util-Format-method-stripScripts'> /**
250 </span> * Strips all script tags
251 * @param {Mixed} value The text from which to strip script tags
252 * @return {String} The stripped text
254 stripScripts : function(v) {
255 return !v ? v : String(v).replace(stripScriptsRe, "");
258 <span id='Ext-util-Format-method-fileSize'> /**
259 </span> * Simple format for a file size (xxx bytes, xxx KB, xxx MB)
260 * @param {Number/String} size The numeric value to format
261 * @return {String} The formatted file size
263 fileSize : function(size) {
264 if (size < 1024) {
265 return size + " bytes";
266 } else if (size < 1048576) {
267 return (Math.round(((size*10) / 1024))/10) + " KB";
269 return (Math.round(((size*10) / 1048576))/10) + " MB";
273 <span id='Ext-util-Format-method-math'> /**
274 </span> * It does simple math for use in a template, for example:<pre><code>
275 * var tpl = new Ext.Template('{value} * 10 = {value:math("* 10")}');
276 * </code></pre>
277 * @return {Function} A function that operates on the passed value.
283 return function(v, a){
285 fns[a] = Ext.functionFactory('v', 'return v ' + a + ';');
291 <span id='Ext-util-Format-method-round'> /**
292 </span> * Rounds the passed number to the required decimal precision.
293 * @param {Number/String} value The numeric value to round.
294 * @param {Number} precision The number of decimal places to which to round the first parameter's value.
295 * @return {Number} The rounded value.
297 round : function(value, precision) {
298 var result = Number(value);
299 if (typeof precision == 'number') {
300 precision = Math.pow(10, precision);
301 result = Math.round(value * precision) / precision;
306 <span id='Ext-util-Format-method-number'> /**
307 </span> * <p>Formats the passed number according to the passed format string.</p>
308 * <p>The number of digits after the decimal separator character specifies the number of
309 * decimal places in the resulting string. The <u>local-specific</u> decimal character is used in the result.</p>
310 * <p>The <i>presence</i> of a thousand separator character in the format string specifies that
311 * the <u>locale-specific</u> thousand separator (if any) is inserted separating thousand groups.</p>
312 * <p>By default, "," is expected as the thousand separator, and "." is expected as the decimal separator.</p>
313 * <p><b>New to Ext4</b></p>
314 * <p>Locale-specific characters are always used in the formatted output when inserting
315 * thousand and decimal separators.</p>
316 * <p>The format string must specify separator characters according to US/UK conventions ("," as the
317 * thousand separator, and "." as the decimal separator)</p>
318 * <p>To allow specification of format strings according to local conventions for separator characters, add
319 * the string <code>/i</code> to the end of the format string.</p>
320 * <div style="margin-left:40px">examples (123456.789):
321 * <div style="margin-left:10px">
322 * 0 - (123456) show only digits, no precision<br>
323 * 0.00 - (123456.78) show only digits, 2 precision<br>
324 * 0.0000 - (123456.7890) show only digits, 4 precision<br>
325 * 0,000 - (123,456) show comma and digits, no precision<br>
326 * 0,000.00 - (123,456.78) show comma and digits, 2 precision<br>
327 * 0,0.00 - (123,456.78) shortcut method, show comma and digits, 2 precision<br>
328 * To allow specification of the formatting string using UK/US grouping characters (,) and decimal (.) for international numbers, add /i to the end.
329 * For example: 0.000,00/i
330 * </div></div>
331 * @param {Number} v The number to format.
332 * @param {String} format The way you would like to format this text.
333 * @return {String} The formatted number.
335 number: function(v, formatString) {
339 v = Ext.Number.from(v, NaN);
343 var comma = UtilFormat.thousandSeparator,
344 dec = UtilFormat.decimalSeparator,
352 // The "/i" suffix allows caller to use a locale-specific formatting string.
353 // Clean the format string by removing all but numerals and the decimal separator.
354 // Then split the format string into pre and post decimal segments according to *what* the
355 // decimal separator is. If they are specifying "/i", they are using the local convention in the format string.
356 if (formatString.substr(formatString.length - 2) == '/i') {
357 if (!I18NFormatCleanRe) {
358 I18NFormatCleanRe = new RegExp('[^\\d\\' + UtilFormat.decimalSeparator + ']','g');
360 formatString = formatString.substr(0, formatString.length - 2);
362 hasComma = formatString.indexOf(comma) != -1;
363 psplit = formatString.replace(I18NFormatCleanRe, '').split(dec);
365 hasComma = formatString.indexOf(',') != -1;
366 psplit = formatString.replace(formatCleanRe, '').split('.');
369 if (1 < psplit.length) {
370 v = v.toFixed(psplit[1].length);
371 } else if(2 < psplit.length) {
374 sourceClass: "Ext.util.Format",
375 sourceMethod: "number",
377 formatString: formatString,
378 msg: "Invalid number format, should have no more than 1 decimal"
385 var fnum = v.toString();
387 psplit = fnum.split('.');
390 var cnum = psplit[0],
393 m = Math.floor(j / 3),
394 n = cnum.length % 3 || 3,
397 for (i = 0; i < j; i += n) {
402 parr[parr.length] = cnum.substr(i, n);
405 fnum = parr.join(comma);
407 fnum += dec + psplit[1];
411 fnum = psplit[0] + dec + psplit[1];
417 * Edge case. If we have a very small negative number it will get rounded to 0,
418 * however the initial check at the top will still report as negative. Replace
419 * everything but 1-9 and check if the string is empty to determine a 0 value.
421 neg = fnum.replace(/[^1-9]/g, '') !== '';
424 return (neg ? '-' : '') + formatString.replace(/[\d,?\.?]+/, fnum);
427 <span id='Ext-util-Format-method-numberRenderer'> /**
428 </span> * Returns a number rendering function that can be reused to apply a number format multiple times efficiently
429 * @param {String} format Any valid number format string for {@link #number}
430 * @return {Function} The number formatting function
432 numberRenderer : function(format) {
434 return UtilFormat.number(v, format);
438 <span id='Ext-util-Format-method-plural'> /**
439 </span> * Selectively do a plural form of a word based on a numeric value. For example, in a template,
440 * {commentCount:plural("Comment")} would result in "1 Comment" if commentCount was 1 or would be "x Comments"
441 * if the value is 0 or greater than 1.
442 * @param {Number} value The value to compare against
443 * @param {String} singular The singular form of the word
444 * @param {String} plural (optional) The plural form of the word (defaults to the singular with an "s")
446 plural : function(v, s, p) {
447 return v +' ' + (v == 1 ? s : (p ? p : s+'s'));
450 <span id='Ext-util-Format-method-nl2br'> /**
451 </span> * Converts newline characters to the HTML tag &lt;br/>
452 * @param {String} The string value to format.
453 * @return {String} The string with embedded &lt;br/> tags in place of newlines.
455 nl2br : function(v) {
456 return Ext.isEmpty(v) ? '' : v.replace(nl2brRe, '<br/>');
459 <span id='Ext-util-Format-method-capitalize'> /**
460 </span> * Capitalize the given string. See {@link Ext.String#capitalize}.
463 capitalize: Ext.String.capitalize,
465 <span id='Ext-util-Format-method-ellipsis'> /**
466 </span> * Truncate a string and add an ellipsis ('...') to the end if it exceeds the specified length.
467 * See {@link Ext.String#ellipsis}.
470 ellipsis: Ext.String.ellipsis,
472 <span id='Ext-util-Format-method-format'> /**
473 </span> * Formats to a string. See {@link Ext.String#format}
476 format: Ext.String.format,
478 <span id='Ext-util-Format-method-htmlDecode'> /**
479 </span> * Convert certain characters (&, <, >, and ') from their HTML character equivalents.
480 * See {@link Ext.String#htmlDecode}.
483 htmlDecode: Ext.String.htmlDecode,
485 <span id='Ext-util-Format-method-htmlEncode'> /**
486 </span> * Convert certain characters (&, <, >, and ') to their HTML character equivalents for literal display in web pages.
487 * See {@link Ext.String#htmlEncode}.
490 htmlEncode: Ext.String.htmlEncode,
492 <span id='Ext-util-Format-method-leftPad'> /**
493 </span> * Adds left padding to a string. See {@link Ext.String#leftPad}
496 leftPad: Ext.String.leftPad,
498 <span id='Ext-util-Format-method-trim'> /**
499 </span> * Trims any whitespace from either side of a string. See {@link Ext.String#trim}.
502 trim : Ext.String.trim,
504 <span id='Ext-util-Format-method-parseBox'> /**
505 </span> * Parses a number or string representing margin sizes into an object. Supports CSS-style margin declarations
506 * (e.g. 10, "10", "10 10", "10 10 10" and "10 10 10 10" are all valid options and would return the same result)
507 * @param {Number|String} v The encoded margins
508 * @return {Object} An object with margin sizes for top, right, bottom and left
510 parseBox : function(box) {
511 if (Ext.isNumber(box)) {
512 box = box.toString();
514 var parts = box.split(' '),
518 parts[1] = parts[2] = parts[3] = parts[0];
529 top :parseInt(parts[0], 10) || 0,
530 right :parseInt(parts[1], 10) || 0,
531 bottom:parseInt(parts[2], 10) || 0,
532 left :parseInt(parts[3], 10) || 0
536 <span id='Ext-util-Format-method-escapeRegex'> /**
537 </span> * Escapes the passed string for use in a regular expression
538 * @param {String} str
541 escapeRegex : function(s) {
542 return s.replace(/([\-.*+?\^${}()|\[\]\/\\])/g, "\\$1");