/ext-4.0.7/docs/source/Format.html
HTML | 547 lines | 491 code | 56 blank | 0 comment | 0 complexity | 22a866756aaba225d7001546d2111403 MD5 | raw file
1<!DOCTYPE html>
2<html>
3<head>
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; }
10 </style>
11 <script type="text/javascript">
12 function highlight() {
13 document.getElementById(location.hash.replace(/#/, "")).className = "highlight";
14 }
15 </script>
16</head>
17<body onload="prettyPrint(); highlight();">
18 <pre class="prettyprint lang-js"><span id='Ext-util-Format'>/**
19</span> * @class Ext.util.Format
20
21This class is a centralized place for formatting functions. It includes
22functions to format various different types of data, such as text, dates and numeric values.
23
24__Localization__
25This class contains several options for localization. These can be set once the library has loaded,
26all calls to the functions from that point will use the locale settings that were specified.
27Options include:
28- thousandSeparator
29- decimalSeparator
30- currenyPrecision
31- currencySign
32- currencyAtEnd
33This class also uses the default date format defined here: {@link Ext.Date#defaultFormat}.
34
35__Using with renderers__
36There are two helper functions that return a new function that can be used in conjunction with
37grid renderers:
38
39 columns: [{
40 dataIndex: 'date',
41 renderer: Ext.util.Format.dateRenderer('Y-m-d')
42 }, {
43 dataIndex: 'time',
44 renderer: Ext.util.Format.numberRenderer('0.000')
45 }]
46
47Functions that only take a single argument can also be passed directly:
48 columns: [{
49 dataIndex: 'cost',
50 renderer: Ext.util.Format.usMoney
51 }, {
52 dataIndex: 'productCode',
53 renderer: Ext.util.Format.uppercase
54 }]
55
56__Using with XTemplates__
57XTemplates can also directly use Ext.util.Format functions:
58
59 new Ext.XTemplate([
60 'Date: {startDate:date("Y-m-d")}',
61 'Cost: {cost:usMoney}'
62 ]);
63
64 * @markdown
65 * @singleton
66 */
67(function() {
68 Ext.ns('Ext.util');
69
70 Ext.util.Format = {};
71 var UtilFormat = Ext.util.Format,
72 stripTagsRE = /<\/?[^>]+>/gi,
73 stripScriptsRe = /(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/ig,
74 nl2brRe = /\r?\n/g,
75
76 // A RegExp to remove from a number format string, all characters except digits and '.'
77 formatCleanRe = /[^\d\.]/g,
78
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.
81 I18NFormatCleanRe;
82
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>
88 */
89 thousandSeparator: ',',
90
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>
95 */
96 decimalSeparator: '.',
97
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>
102 */
103 currencyPrecision: 2,
104
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>
109 */
110 currencySign: '$',
111
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>
117 */
118 currencyAtEnd: false,
119
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
124 */
125 undef : function(value) {
126 return value !== undefined ? value : "";
127 },
128
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 "")
133 * @return {String}
134 */
135 defaultValue : function(value, defaultValue) {
136 return value !== undefined && value !== '' ? value : defaultValue;
137 },
138
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
145 */
146 substr : function(value, start, length) {
147 return String(value).substr(start, length);
148 },
149
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
154 */
155 lowercase : function(value) {
156 return String(value).toLowerCase();
157 },
158
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
163 */
164 uppercase : function(value) {
165 return String(value).toUpperCase();
166 },
167
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
172 */
173 usMoney : function(v) {
174 return UtilFormat.currency(v, '$', 2);
175 },
176
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
184 */
185 currency: function(v, currencySign, decimals, end) {
186 var negativeSign = '',
187 format = ",0",
188 i = 0;
189 v = v - 0;
190 if (v < 0) {
191 v = -v;
192 negativeSign = '-';
193 }
194 decimals = decimals || UtilFormat.currencyPrecision;
195 format += format + (decimals > 0 ? '.' : '');
196 for (; i < decimals; i++) {
197 format += '0';
198 }
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);
202 } else {
203 return Ext.String.format("{0}{1}{2}", negativeSign, currencySign || UtilFormat.currencySign, v);
204 }
205 },
206
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.
213 */
214 date: function(v, format) {
215 if (!v) {
216 return "";
217 }
218 if (!Ext.isDate(v)) {
219 v = new Date(Date.parse(v));
220 }
221 return Ext.Date.dateFormat(v, format || Ext.Date.defaultFormat);
222 },
223
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
228 */
229 dateRenderer : function(format) {
230 return function(v) {
231 return UtilFormat.date(v, format);
232 };
233 },
234
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
239 */
240 stripTags : function(v) {
241 return !v ? v : String(v).replace(stripTagsRE, "");
242 },
243
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
248 */
249 stripScripts : function(v) {
250 return !v ? v : String(v).replace(stripScriptsRe, "");
251 },
252
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
257 */
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";
263 } else {
264 return (Math.round(((size*10) / 1048576))/10) + " MB";
265 }
266 },
267
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.
273 * @method
274 */
275 math : function(){
276 var fns = {};
277
278 return function(v, a){
279 if (!fns[a]) {
280 fns[a] = Ext.functionFactory('v', 'return v ' + a + ';');
281 }
282 return fns[a](v);
283 };
284 }(),
285
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.
291 */
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;
297 }
298 return result;
299 },
300
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.
329 */
330 number: function(v, formatString) {
331 if (!formatString) {
332 return v;
333 }
334 v = Ext.Number.from(v, NaN);
335 if (isNaN(v)) {
336 return '';
337 }
338 var comma = UtilFormat.thousandSeparator,
339 dec = UtilFormat.decimalSeparator,
340 i18n = false,
341 neg = v < 0,
342 hasComma,
343 psplit;
344
345 v = Math.abs(v);
346
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');
354 }
355 formatString = formatString.substr(0, formatString.length - 2);
356 i18n = true;
357 hasComma = formatString.indexOf(comma) != -1;
358 psplit = formatString.replace(I18NFormatCleanRe, '').split(dec);
359 } else {
360 hasComma = formatString.indexOf(',') != -1;
361 psplit = formatString.replace(formatCleanRe, '').split('.');
362 }
363
364 if (1 < psplit.length) {
365 v = v.toFixed(psplit[1].length);
366 } else if(2 < psplit.length) {
367 //<debug>
368 Ext.Error.raise({
369 sourceClass: "Ext.util.Format",
370 sourceMethod: "number",
371 value: v,
372 formatString: formatString,
373 msg: "Invalid number format, should have no more than 1 decimal"
374 });
375 //</debug>
376 } else {
377 v = v.toFixed(0);
378 }
379
380 var fnum = v.toString();
381
382 psplit = fnum.split('.');
383
384 if (hasComma) {
385 var cnum = psplit[0],
386 parr = [],
387 j = cnum.length,
388 m = Math.floor(j / 3),
389 n = cnum.length % 3 || 3,
390 i;
391
392 for (i = 0; i < j; i += n) {
393 if (i !== 0) {
394 n = 3;
395 }
396
397 parr[parr.length] = cnum.substr(i, n);
398 m -= 1;
399 }
400 fnum = parr.join(comma);
401 if (psplit[1]) {
402 fnum += dec + psplit[1];
403 }
404 } else {
405 if (psplit[1]) {
406 fnum = psplit[0] + dec + psplit[1];
407 }
408 }
409
410 if (neg) {
411 /*
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.
415 */
416 neg = fnum.replace(/[^1-9]/g, '') !== '';
417 }
418
419 return (neg ? '-' : '') + formatString.replace(/[\d,?\.?]+/, fnum);
420 },
421
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
426 */
427 numberRenderer : function(format) {
428 return function(v) {
429 return UtilFormat.number(v, format);
430 };
431 },
432
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")
440 */
441 plural : function(v, s, p) {
442 return v +' ' + (v == 1 ? s : (p ? p : s+'s'));
443 },
444
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.
449 */
450 nl2br : function(v) {
451 return Ext.isEmpty(v) ? '' : v.replace(nl2brRe, '<br/>');
452 },
453
454<span id='Ext-util-Format-method-capitalize'> /**
455</span> * Alias for {@link Ext.String#capitalize}.
456 * @method
457 * @alias Ext.String#capitalize
458 */
459 capitalize: Ext.String.capitalize,
460
461<span id='Ext-util-Format-method-ellipsis'> /**
462</span> * Alias for {@link Ext.String#ellipsis}.
463 * @method
464 * @alias Ext.String#ellipsis
465 */
466 ellipsis: Ext.String.ellipsis,
467
468<span id='Ext-util-Format-method-format'> /**
469</span> * Alias for {@link Ext.String#format}.
470 * @method
471 * @alias Ext.String#format
472 */
473 format: Ext.String.format,
474
475<span id='Ext-util-Format-method-htmlDecode'> /**
476</span> * Alias for {@link Ext.String#htmlDecode}.
477 * @method
478 * @alias Ext.String#htmlDecode
479 */
480 htmlDecode: Ext.String.htmlDecode,
481
482<span id='Ext-util-Format-method-htmlEncode'> /**
483</span> * Alias for {@link Ext.String#htmlEncode}.
484 * @method
485 * @alias Ext.String#htmlEncode
486 */
487 htmlEncode: Ext.String.htmlEncode,
488
489<span id='Ext-util-Format-method-leftPad'> /**
490</span> * Alias for {@link Ext.String#leftPad}.
491 * @method
492 * @alias Ext.String#leftPad
493 */
494 leftPad: Ext.String.leftPad,
495
496<span id='Ext-util-Format-method-trim'> /**
497</span> * Alias for {@link Ext.String#trim}.
498 * @method
499 * @alias Ext.String#trim
500 */
501 trim : Ext.String.trim,
502
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
508 */
509 parseBox : function(box) {
510 if (Ext.isNumber(box)) {
511 box = box.toString();
512 }
513 var parts = box.split(' '),
514 ln = parts.length;
515
516 if (ln == 1) {
517 parts[1] = parts[2] = parts[3] = parts[0];
518 }
519 else if (ln == 2) {
520 parts[2] = parts[0];
521 parts[3] = parts[1];
522 }
523 else if (ln == 3) {
524 parts[3] = parts[1];
525 }
526
527 return {
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
532 };
533 },
534
535<span id='Ext-util-Format-method-escapeRegex'> /**
536</span> * Escapes the passed string for use in a regular expression
537 * @param {String} str
538 * @return {String}
539 */
540 escapeRegex : function(s) {
541 return s.replace(/([\-.*+?\^${}()|\[\]\/\\])/g, "\\$1");
542 }
543 });
544})();
545</pre>
546</body>
547</html>