4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
5 <title>The source code</title>
6 <link href="../resources/prettify/prettify.css" type="text/css" rel="stylesheet" />
7 <script type="text/javascript" src="../resources/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. 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> * @property {String} thousandSeparator
86 * <p>The character that the {@link #number} function uses as a thousand separator.</p>
87 * <p>This may be overridden in a locale file.</p>
89 thousandSeparator: ',',
91 <span id='Ext-util-Format-property-decimalSeparator'> /**
92 </span> * @property {String} decimalSeparator
93 * <p>The character that the {@link #number} function uses as a decimal point.</p>
94 * <p>This may be overridden in a locale file.</p>
96 decimalSeparator: '.',
98 <span id='Ext-util-Format-property-currencyPrecision'> /**
99 </span> * @property {Number} currencyPrecision
100 * <p>The number of decimal places that the {@link #currency} function displays.</p>
101 * <p>This may be overridden in a locale file.</p>
103 currencyPrecision: 2,
105 <span id='Ext-util-Format-property-currencySign'> /**
106 </span> * @property {String} currencySign
107 * <p>The currency sign that the {@link #currency} function displays.</p>
108 * <p>This may be overridden in a locale file.</p>
112 <span id='Ext-util-Format-property-currencyAtEnd'> /**
113 </span> * @property {Boolean} currencyAtEnd
114 * <p>This may be set to <code>true</code> to make the {@link #currency} function
115 * append the currency sign to the formatted value.</p>
116 * <p>This may be overridden in a locale file.</p>
118 currencyAtEnd: false,
120 <span id='Ext-util-Format-method-undef'> /**
121 </span> * Checks a reference and converts it to empty string if it is undefined
122 * @param {Object} value Reference to check
123 * @return {Object} Empty string if converted, otherwise the original value
125 undef : function(value) {
126 return value !== undefined ? value : "";
129 <span id='Ext-util-Format-method-defaultValue'> /**
130 </span> * Checks a reference and converts it to the default value if it's empty
131 * @param {Object} value Reference to check
132 * @param {String} defaultValue The value to insert of it's undefined (defaults to "")
135 defaultValue : function(value, defaultValue) {
136 return value !== undefined && value !== '' ? value : defaultValue;
139 <span id='Ext-util-Format-method-substr'> /**
140 </span> * Returns a substring from within an original string
141 * @param {String} value The original text
142 * @param {Number} start The start index of the substring
143 * @param {Number} length The length of the substring
144 * @return {String} The substring
146 substr : function(value, start, length) {
147 return String(value).substr(start, length);
150 <span id='Ext-util-Format-method-lowercase'> /**
151 </span> * Converts a string to all lower case letters
152 * @param {String} value The text to convert
153 * @return {String} The converted text
155 lowercase : function(value) {
156 return String(value).toLowerCase();
159 <span id='Ext-util-Format-method-uppercase'> /**
160 </span> * Converts a string to all upper case letters
161 * @param {String} value The text to convert
162 * @return {String} The converted text
164 uppercase : function(value) {
165 return String(value).toUpperCase();
168 <span id='Ext-util-Format-method-usMoney'> /**
169 </span> * Format a number as US currency
170 * @param {Number/String} value The numeric value to format
171 * @return {String} The formatted currency string
173 usMoney : function(v) {
174 return UtilFormat.currency(v, '$', 2);
177 <span id='Ext-util-Format-method-currency'> /**
178 </span> * Format a number as a currency
179 * @param {Number/String} value The numeric value to format
180 * @param {String} sign The currency sign to use (defaults to {@link #currencySign})
181 * @param {Number} decimals The number of decimals to use for the currency (defaults to {@link #currencyPrecision})
182 * @param {Boolean} end True if the currency sign should be at the end of the string (defaults to {@link #currencyAtEnd})
183 * @return {String} The formatted currency string
185 currency: function(v, currencySign, decimals, end) {
186 var negativeSign = '',
187 format = ",0",
194 decimals = decimals || UtilFormat.currencyPrecision;
195 format += format + (decimals > 0 ? '.' : '');
196 for (; i < decimals; i++) {
199 v = UtilFormat.number(v, format);
200 if ((end || UtilFormat.currencyAtEnd) === true) {
201 return Ext.String.format("{0}{1}{2}", negativeSign, v, currencySign || UtilFormat.currencySign);
203 return Ext.String.format("{0}{1}{2}", negativeSign, currencySign || UtilFormat.currencySign, v);
207 <span id='Ext-util-Format-method-date'> /**
208 </span> * Formats the passed date using the specified format pattern.
209 * @param {String/Date} value The value to format. If a string is passed, it is converted to a Date by the Javascript
210 * Date object's <a href="http://www.w3schools.com/jsref/jsref_parse.asp">parse()</a> method.
211 * @param {String} format (Optional) Any valid date format string. Defaults to {@link Ext.Date#defaultFormat}.
212 * @return {String} The formatted date string.
214 date: function(v, format) {
218 if (!Ext.isDate(v)) {
219 v = new Date(Date.parse(v));
221 return Ext.Date.dateFormat(v, format || Ext.Date.defaultFormat);
224 <span id='Ext-util-Format-method-dateRenderer'> /**
225 </span> * Returns a date rendering function that can be reused to apply a date format multiple times efficiently
226 * @param {String} format Any valid date format string. Defaults to {@link Ext.Date#defaultFormat}.
227 * @return {Function} The date formatting function
229 dateRenderer : function(format) {
231 return UtilFormat.date(v, format);
235 <span id='Ext-util-Format-method-stripTags'> /**
236 </span> * Strips all HTML tags
237 * @param {Object} value The text from which to strip tags
238 * @return {String} The stripped text
240 stripTags : function(v) {
241 return !v ? v : String(v).replace(stripTagsRE, "");
244 <span id='Ext-util-Format-method-stripScripts'> /**
245 </span> * Strips all script tags
246 * @param {Object} value The text from which to strip script tags
247 * @return {String} The stripped text
249 stripScripts : function(v) {
250 return !v ? v : String(v).replace(stripScriptsRe, "");
253 <span id='Ext-util-Format-method-fileSize'> /**
254 </span> * Simple format for a file size (xxx bytes, xxx KB, xxx MB)
255 * @param {Number/String} size The numeric value to format
256 * @return {String} The formatted file size
258 fileSize : function(size) {
259 if (size < 1024) {
260 return size + " bytes";
261 } else if (size < 1048576) {
262 return (Math.round(((size*10) / 1024))/10) + " KB";
264 return (Math.round(((size*10) / 1048576))/10) + " MB";
268 <span id='Ext-util-Format-method-math'> /**
269 </span> * It does simple math for use in a template, for example:<pre><code>
270 * var tpl = new Ext.Template('{value} * 10 = {value:math("* 10")}');
271 * </code></pre>
272 * @return {Function} A function that operates on the passed value.
278 return function(v, a){
280 fns[a] = Ext.functionFactory('v', 'return v ' + a + ';');
286 <span id='Ext-util-Format-method-round'> /**
287 </span> * Rounds the passed number to the required decimal precision.
288 * @param {Number/String} value The numeric value to round.
289 * @param {Number} precision The number of decimal places to which to round the first parameter's value.
290 * @return {Number} The rounded value.
292 round : function(value, precision) {
293 var result = Number(value);
294 if (typeof precision == 'number') {
295 precision = Math.pow(10, precision);
296 result = Math.round(value * precision) / precision;
301 <span id='Ext-util-Format-method-number'> /**
302 </span> * <p>Formats the passed number according to the passed format string.</p>
303 * <p>The number of digits after the decimal separator character specifies the number of
304 * decimal places in the resulting string. The <u>local-specific</u> decimal character is used in the result.</p>
305 * <p>The <i>presence</i> of a thousand separator character in the format string specifies that
306 * the <u>locale-specific</u> thousand separator (if any) is inserted separating thousand groups.</p>
307 * <p>By default, "," is expected as the thousand separator, and "." is expected as the decimal separator.</p>
308 * <p><b>New to Ext JS 4</b></p>
309 * <p>Locale-specific characters are always used in the formatted output when inserting
310 * thousand and decimal separators.</p>
311 * <p>The format string must specify separator characters according to US/UK conventions ("," as the
312 * thousand separator, and "." as the decimal separator)</p>
313 * <p>To allow specification of format strings according to local conventions for separator characters, add
314 * the string <code>/i</code> to the end of the format string.</p>
315 * <div style="margin-left:40px">examples (123456.789):
316 * <div style="margin-left:10px">
317 * 0 - (123456) show only digits, no precision<br>
318 * 0.00 - (123456.78) show only digits, 2 precision<br>
319 * 0.0000 - (123456.7890) show only digits, 4 precision<br>
320 * 0,000 - (123,456) show comma and digits, no precision<br>
321 * 0,000.00 - (123,456.78) show comma and digits, 2 precision<br>
322 * 0,0.00 - (123,456.78) shortcut method, show comma and digits, 2 precision<br>
323 * To allow specification of the formatting string using UK/US grouping characters (,) and decimal (.) for international numbers, add /i to the end.
324 * For example: 0.000,00/i
325 * </div></div>
326 * @param {Number} v The number to format.
327 * @param {String} format The way you would like to format this text.
328 * @return {String} The formatted number.
330 number: function(v, formatString) {
334 v = Ext.Number.from(v, NaN);
338 var comma = UtilFormat.thousandSeparator,
339 dec = UtilFormat.decimalSeparator,
347 // The "/i" suffix allows caller to use a locale-specific formatting string.
348 // Clean the format string by removing all but numerals and the decimal separator.
349 // Then split the format string into pre and post decimal segments according to *what* the
350 // decimal separator is. If they are specifying "/i", they are using the local convention in the format string.
351 if (formatString.substr(formatString.length - 2) == '/i') {
352 if (!I18NFormatCleanRe) {
353 I18NFormatCleanRe = new RegExp('[^\\d\\' + UtilFormat.decimalSeparator + ']','g');
355 formatString = formatString.substr(0, formatString.length - 2);
357 hasComma = formatString.indexOf(comma) != -1;
358 psplit = formatString.replace(I18NFormatCleanRe, '').split(dec);
360 hasComma = formatString.indexOf(',') != -1;
361 psplit = formatString.replace(formatCleanRe, '').split('.');
364 if (1 < psplit.length) {
365 v = v.toFixed(psplit[1].length);
366 } else if(2 < psplit.length) {
369 sourceClass: "Ext.util.Format",
370 sourceMethod: "number",
372 formatString: formatString,
373 msg: "Invalid number format, should have no more than 1 decimal"
380 var fnum = v.toString();
382 psplit = fnum.split('.');
385 var cnum = psplit[0],
388 m = Math.floor(j / 3),
389 n = cnum.length % 3 || 3,
392 for (i = 0; i < j; i += n) {
397 parr[parr.length] = cnum.substr(i, n);
400 fnum = parr.join(comma);
402 fnum += dec + psplit[1];
406 fnum = psplit[0] + dec + psplit[1];
412 * Edge case. If we have a very small negative number it will get rounded to 0,
413 * however the initial check at the top will still report as negative. Replace
414 * everything but 1-9 and check if the string is empty to determine a 0 value.
416 neg = fnum.replace(/[^1-9]/g, '') !== '';
419 return (neg ? '-' : '') + formatString.replace(/[\d,?\.?]+/, fnum);
422 <span id='Ext-util-Format-method-numberRenderer'> /**
423 </span> * Returns a number rendering function that can be reused to apply a number format multiple times efficiently
424 * @param {String} format Any valid number format string for {@link #number}
425 * @return {Function} The number formatting function
427 numberRenderer : function(format) {
429 return UtilFormat.number(v, format);
433 <span id='Ext-util-Format-method-plural'> /**
434 </span> * Selectively do a plural form of a word based on a numeric value. For example, in a template,
435 * {commentCount:plural("Comment")} would result in "1 Comment" if commentCount was 1 or would be "x Comments"
436 * if the value is 0 or greater than 1.
437 * @param {Number} value The value to compare against
438 * @param {String} singular The singular form of the word
439 * @param {String} plural (optional) The plural form of the word (defaults to the singular with an "s")
441 plural : function(v, s, p) {
442 return v +' ' + (v == 1 ? s : (p ? p : s+'s'));
445 <span id='Ext-util-Format-method-nl2br'> /**
446 </span> * Converts newline characters to the HTML tag &lt;br/>
447 * @param {String} The string value to format.
448 * @return {String} The string with embedded &lt;br/> tags in place of newlines.
450 nl2br : function(v) {
451 return Ext.isEmpty(v) ? '' : v.replace(nl2brRe, '<br/>');
454 <span id='Ext-util-Format-method-capitalize'> /**
455 </span> * Alias for {@link Ext.String#capitalize}.
457 * @alias Ext.String#capitalize
459 capitalize: Ext.String.capitalize,
461 <span id='Ext-util-Format-method-ellipsis'> /**
462 </span> * Alias for {@link Ext.String#ellipsis}.
464 * @alias Ext.String#ellipsis
466 ellipsis: Ext.String.ellipsis,
468 <span id='Ext-util-Format-method-format'> /**
469 </span> * Alias for {@link Ext.String#format}.
471 * @alias Ext.String#format
473 format: Ext.String.format,
475 <span id='Ext-util-Format-method-htmlDecode'> /**
476 </span> * Alias for {@link Ext.String#htmlDecode}.
478 * @alias Ext.String#htmlDecode
480 htmlDecode: Ext.String.htmlDecode,
482 <span id='Ext-util-Format-method-htmlEncode'> /**
483 </span> * Alias for {@link Ext.String#htmlEncode}.
485 * @alias Ext.String#htmlEncode
487 htmlEncode: Ext.String.htmlEncode,
489 <span id='Ext-util-Format-method-leftPad'> /**
490 </span> * Alias for {@link Ext.String#leftPad}.
492 * @alias Ext.String#leftPad
494 leftPad: Ext.String.leftPad,
496 <span id='Ext-util-Format-method-trim'> /**
497 </span> * Alias for {@link Ext.String#trim}.
499 * @alias Ext.String#trim
501 trim : Ext.String.trim,
503 <span id='Ext-util-Format-method-parseBox'> /**
504 </span> * Parses a number or string representing margin sizes into an object. Supports CSS-style margin declarations
505 * (e.g. 10, "10", "10 10", "10 10 10" and "10 10 10 10" are all valid options and would return the same result)
506 * @param {Number/String} v The encoded margins
507 * @return {Object} An object with margin sizes for top, right, bottom and left
509 parseBox : function(box) {
510 if (Ext.isNumber(box)) {
511 box = box.toString();
513 var parts = box.split(' '),
517 parts[1] = parts[2] = parts[3] = parts[0];
528 top :parseInt(parts[0], 10) || 0,
529 right :parseInt(parts[1], 10) || 0,
530 bottom:parseInt(parts[2], 10) || 0,
531 left :parseInt(parts[3], 10) || 0
535 <span id='Ext-util-Format-method-escapeRegex'> /**
536 </span> * Escapes the passed string for use in a regular expression
537 * @param {String} str
540 escapeRegex : function(s) {
541 return s.replace(/([\-.*+?\^${}()|\[\]\/\\])/g, "\\$1");