/ext-4.0.7/docs/source/Format.html

https://bitbucket.org/srogerf/javascript · 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. This class is a centralized place for formatting functions. It includes
  21. functions to format various different types of data, such as text, dates and numeric values.
  22. __Localization__
  23. This class contains several options for localization. These can be set once the library has loaded,
  24. all calls to the functions from that point will use the locale settings that were specified.
  25. Options include:
  26. - thousandSeparator
  27. - decimalSeparator
  28. - currenyPrecision
  29. - currencySign
  30. - currencyAtEnd
  31. This class also uses the default date format defined here: {@link Ext.Date#defaultFormat}.
  32. __Using with renderers__
  33. There are two helper functions that return a new function that can be used in conjunction with
  34. grid renderers:
  35. columns: [{
  36. dataIndex: 'date',
  37. renderer: Ext.util.Format.dateRenderer('Y-m-d')
  38. }, {
  39. dataIndex: 'time',
  40. renderer: Ext.util.Format.numberRenderer('0.000')
  41. }]
  42. Functions that only take a single argument can also be passed directly:
  43. columns: [{
  44. dataIndex: 'cost',
  45. renderer: Ext.util.Format.usMoney
  46. }, {
  47. dataIndex: 'productCode',
  48. renderer: Ext.util.Format.uppercase
  49. }]
  50. __Using with XTemplates__
  51. XTemplates can also directly use Ext.util.Format functions:
  52. new Ext.XTemplate([
  53. 'Date: {startDate:date(&quot;Y-m-d&quot;)}',
  54. 'Cost: {cost:usMoney}'
  55. ]);
  56. * @markdown
  57. * @singleton
  58. */
  59. (function() {
  60. Ext.ns('Ext.util');
  61. Ext.util.Format = {};
  62. var UtilFormat = Ext.util.Format,
  63. stripTagsRE = /&lt;\/?[^&gt;]+&gt;/gi,
  64. stripScriptsRe = /(?:&lt;script.*?&gt;)((\n|\r|.)*?)(?:&lt;\/script&gt;)/ig,
  65. nl2brRe = /\r?\n/g,
  66. // A RegExp to remove from a number format string, all characters except digits and '.'
  67. formatCleanRe = /[^\d\.]/g,
  68. // A RegExp to remove from a number format string, all characters except digits and the local decimal separator.
  69. // Created on first use. The local decimal separator character must be initialized for this to be created.
  70. I18NFormatCleanRe;
  71. Ext.apply(UtilFormat, {
  72. <span id='Ext-util-Format-property-thousandSeparator'> /**
  73. </span> * @property {String} thousandSeparator
  74. * &lt;p&gt;The character that the {@link #number} function uses as a thousand separator.&lt;/p&gt;
  75. * &lt;p&gt;This may be overridden in a locale file.&lt;/p&gt;
  76. */
  77. thousandSeparator: ',',
  78. <span id='Ext-util-Format-property-decimalSeparator'> /**
  79. </span> * @property {String} decimalSeparator
  80. * &lt;p&gt;The character that the {@link #number} function uses as a decimal point.&lt;/p&gt;
  81. * &lt;p&gt;This may be overridden in a locale file.&lt;/p&gt;
  82. */
  83. decimalSeparator: '.',
  84. <span id='Ext-util-Format-property-currencyPrecision'> /**
  85. </span> * @property {Number} currencyPrecision
  86. * &lt;p&gt;The number of decimal places that the {@link #currency} function displays.&lt;/p&gt;
  87. * &lt;p&gt;This may be overridden in a locale file.&lt;/p&gt;
  88. */
  89. currencyPrecision: 2,
  90. <span id='Ext-util-Format-property-currencySign'> /**
  91. </span> * @property {String} currencySign
  92. * &lt;p&gt;The currency sign that the {@link #currency} function displays.&lt;/p&gt;
  93. * &lt;p&gt;This may be overridden in a locale file.&lt;/p&gt;
  94. */
  95. currencySign: '$',
  96. <span id='Ext-util-Format-property-currencyAtEnd'> /**
  97. </span> * @property {Boolean} currencyAtEnd
  98. * &lt;p&gt;This may be set to &lt;code&gt;true&lt;/code&gt; to make the {@link #currency} function
  99. * append the currency sign to the formatted value.&lt;/p&gt;
  100. * &lt;p&gt;This may be overridden in a locale file.&lt;/p&gt;
  101. */
  102. currencyAtEnd: false,
  103. <span id='Ext-util-Format-method-undef'> /**
  104. </span> * Checks a reference and converts it to empty string if it is undefined
  105. * @param {Object} value Reference to check
  106. * @return {Object} Empty string if converted, otherwise the original value
  107. */
  108. undef : function(value) {
  109. return value !== undefined ? value : &quot;&quot;;
  110. },
  111. <span id='Ext-util-Format-method-defaultValue'> /**
  112. </span> * Checks a reference and converts it to the default value if it's empty
  113. * @param {Object} value Reference to check
  114. * @param {String} defaultValue The value to insert of it's undefined (defaults to &quot;&quot;)
  115. * @return {String}
  116. */
  117. defaultValue : function(value, defaultValue) {
  118. return value !== undefined &amp;&amp; value !== '' ? value : defaultValue;
  119. },
  120. <span id='Ext-util-Format-method-substr'> /**
  121. </span> * Returns a substring from within an original string
  122. * @param {String} value The original text
  123. * @param {Number} start The start index of the substring
  124. * @param {Number} length The length of the substring
  125. * @return {String} The substring
  126. */
  127. substr : function(value, start, length) {
  128. return String(value).substr(start, length);
  129. },
  130. <span id='Ext-util-Format-method-lowercase'> /**
  131. </span> * Converts a string to all lower case letters
  132. * @param {String} value The text to convert
  133. * @return {String} The converted text
  134. */
  135. lowercase : function(value) {
  136. return String(value).toLowerCase();
  137. },
  138. <span id='Ext-util-Format-method-uppercase'> /**
  139. </span> * Converts a string to all upper case letters
  140. * @param {String} value The text to convert
  141. * @return {String} The converted text
  142. */
  143. uppercase : function(value) {
  144. return String(value).toUpperCase();
  145. },
  146. <span id='Ext-util-Format-method-usMoney'> /**
  147. </span> * Format a number as US currency
  148. * @param {Number/String} value The numeric value to format
  149. * @return {String} The formatted currency string
  150. */
  151. usMoney : function(v) {
  152. return UtilFormat.currency(v, '$', 2);
  153. },
  154. <span id='Ext-util-Format-method-currency'> /**
  155. </span> * Format a number as a currency
  156. * @param {Number/String} value The numeric value to format
  157. * @param {String} sign The currency sign to use (defaults to {@link #currencySign})
  158. * @param {Number} decimals The number of decimals to use for the currency (defaults to {@link #currencyPrecision})
  159. * @param {Boolean} end True if the currency sign should be at the end of the string (defaults to {@link #currencyAtEnd})
  160. * @return {String} The formatted currency string
  161. */
  162. currency: function(v, currencySign, decimals, end) {
  163. var negativeSign = '',
  164. format = &quot;,0&quot;,
  165. i = 0;
  166. v = v - 0;
  167. if (v &lt; 0) {
  168. v = -v;
  169. negativeSign = '-';
  170. }
  171. decimals = decimals || UtilFormat.currencyPrecision;
  172. format += format + (decimals &gt; 0 ? '.' : '');
  173. for (; i &lt; decimals; i++) {
  174. format += '0';
  175. }
  176. v = UtilFormat.number(v, format);
  177. if ((end || UtilFormat.currencyAtEnd) === true) {
  178. return Ext.String.format(&quot;{0}{1}{2}&quot;, negativeSign, v, currencySign || UtilFormat.currencySign);
  179. } else {
  180. return Ext.String.format(&quot;{0}{1}{2}&quot;, negativeSign, currencySign || UtilFormat.currencySign, v);
  181. }
  182. },
  183. <span id='Ext-util-Format-method-date'> /**
  184. </span> * Formats the passed date using the specified format pattern.
  185. * @param {String/Date} value The value to format. If a string is passed, it is converted to a Date by the Javascript
  186. * Date object's &lt;a href=&quot;http://www.w3schools.com/jsref/jsref_parse.asp&quot;&gt;parse()&lt;/a&gt; method.
  187. * @param {String} format (Optional) Any valid date format string. Defaults to {@link Ext.Date#defaultFormat}.
  188. * @return {String} The formatted date string.
  189. */
  190. date: function(v, format) {
  191. if (!v) {
  192. return &quot;&quot;;
  193. }
  194. if (!Ext.isDate(v)) {
  195. v = new Date(Date.parse(v));
  196. }
  197. return Ext.Date.dateFormat(v, format || Ext.Date.defaultFormat);
  198. },
  199. <span id='Ext-util-Format-method-dateRenderer'> /**
  200. </span> * Returns a date rendering function that can be reused to apply a date format multiple times efficiently
  201. * @param {String} format Any valid date format string. Defaults to {@link Ext.Date#defaultFormat}.
  202. * @return {Function} The date formatting function
  203. */
  204. dateRenderer : function(format) {
  205. return function(v) {
  206. return UtilFormat.date(v, format);
  207. };
  208. },
  209. <span id='Ext-util-Format-method-stripTags'> /**
  210. </span> * Strips all HTML tags
  211. * @param {Object} value The text from which to strip tags
  212. * @return {String} The stripped text
  213. */
  214. stripTags : function(v) {
  215. return !v ? v : String(v).replace(stripTagsRE, &quot;&quot;);
  216. },
  217. <span id='Ext-util-Format-method-stripScripts'> /**
  218. </span> * Strips all script tags
  219. * @param {Object} value The text from which to strip script tags
  220. * @return {String} The stripped text
  221. */
  222. stripScripts : function(v) {
  223. return !v ? v : String(v).replace(stripScriptsRe, &quot;&quot;);
  224. },
  225. <span id='Ext-util-Format-method-fileSize'> /**
  226. </span> * Simple format for a file size (xxx bytes, xxx KB, xxx MB)
  227. * @param {Number/String} size The numeric value to format
  228. * @return {String} The formatted file size
  229. */
  230. fileSize : function(size) {
  231. if (size &lt; 1024) {
  232. return size + &quot; bytes&quot;;
  233. } else if (size &lt; 1048576) {
  234. return (Math.round(((size*10) / 1024))/10) + &quot; KB&quot;;
  235. } else {
  236. return (Math.round(((size*10) / 1048576))/10) + &quot; MB&quot;;
  237. }
  238. },
  239. <span id='Ext-util-Format-method-math'> /**
  240. </span> * It does simple math for use in a template, for example:&lt;pre&gt;&lt;code&gt;
  241. * var tpl = new Ext.Template('{value} * 10 = {value:math(&quot;* 10&quot;)}');
  242. * &lt;/code&gt;&lt;/pre&gt;
  243. * @return {Function} A function that operates on the passed value.
  244. * @method
  245. */
  246. math : function(){
  247. var fns = {};
  248. return function(v, a){
  249. if (!fns[a]) {
  250. fns[a] = Ext.functionFactory('v', 'return v ' + a + ';');
  251. }
  252. return fns[a](v);
  253. };
  254. }(),
  255. <span id='Ext-util-Format-method-round'> /**
  256. </span> * Rounds the passed number to the required decimal precision.
  257. * @param {Number/String} value The numeric value to round.
  258. * @param {Number} precision The number of decimal places to which to round the first parameter's value.
  259. * @return {Number} The rounded value.
  260. */
  261. round : function(value, precision) {
  262. var result = Number(value);
  263. if (typeof precision == 'number') {
  264. precision = Math.pow(10, precision);
  265. result = Math.round(value * precision) / precision;
  266. }
  267. return result;
  268. },
  269. <span id='Ext-util-Format-method-number'> /**
  270. </span> * &lt;p&gt;Formats the passed number according to the passed format string.&lt;/p&gt;
  271. * &lt;p&gt;The number of digits after the decimal separator character specifies the number of
  272. * decimal places in the resulting string. The &lt;u&gt;local-specific&lt;/u&gt; decimal character is used in the result.&lt;/p&gt;
  273. * &lt;p&gt;The &lt;i&gt;presence&lt;/i&gt; of a thousand separator character in the format string specifies that
  274. * the &lt;u&gt;locale-specific&lt;/u&gt; thousand separator (if any) is inserted separating thousand groups.&lt;/p&gt;
  275. * &lt;p&gt;By default, &quot;,&quot; is expected as the thousand separator, and &quot;.&quot; is expected as the decimal separator.&lt;/p&gt;
  276. * &lt;p&gt;&lt;b&gt;New to Ext JS 4&lt;/b&gt;&lt;/p&gt;
  277. * &lt;p&gt;Locale-specific characters are always used in the formatted output when inserting
  278. * thousand and decimal separators.&lt;/p&gt;
  279. * &lt;p&gt;The format string must specify separator characters according to US/UK conventions (&quot;,&quot; as the
  280. * thousand separator, and &quot;.&quot; as the decimal separator)&lt;/p&gt;
  281. * &lt;p&gt;To allow specification of format strings according to local conventions for separator characters, add
  282. * the string &lt;code&gt;/i&lt;/code&gt; to the end of the format string.&lt;/p&gt;
  283. * &lt;div style=&quot;margin-left:40px&quot;&gt;examples (123456.789):
  284. * &lt;div style=&quot;margin-left:10px&quot;&gt;
  285. * 0 - (123456) show only digits, no precision&lt;br&gt;
  286. * 0.00 - (123456.78) show only digits, 2 precision&lt;br&gt;
  287. * 0.0000 - (123456.7890) show only digits, 4 precision&lt;br&gt;
  288. * 0,000 - (123,456) show comma and digits, no precision&lt;br&gt;
  289. * 0,000.00 - (123,456.78) show comma and digits, 2 precision&lt;br&gt;
  290. * 0,0.00 - (123,456.78) shortcut method, show comma and digits, 2 precision&lt;br&gt;
  291. * To allow specification of the formatting string using UK/US grouping characters (,) and decimal (.) for international numbers, add /i to the end.
  292. * For example: 0.000,00/i
  293. * &lt;/div&gt;&lt;/div&gt;
  294. * @param {Number} v The number to format.
  295. * @param {String} format The way you would like to format this text.
  296. * @return {String} The formatted number.
  297. */
  298. number: function(v, formatString) {
  299. if (!formatString) {
  300. return v;
  301. }
  302. v = Ext.Number.from(v, NaN);
  303. if (isNaN(v)) {
  304. return '';
  305. }
  306. var comma = UtilFormat.thousandSeparator,
  307. dec = UtilFormat.decimalSeparator,
  308. i18n = false,
  309. neg = v &lt; 0,
  310. hasComma,
  311. psplit;
  312. v = Math.abs(v);
  313. // The &quot;/i&quot; suffix allows caller to use a locale-specific formatting string.
  314. // Clean the format string by removing all but numerals and the decimal separator.
  315. // Then split the format string into pre and post decimal segments according to *what* the
  316. // decimal separator is. If they are specifying &quot;/i&quot;, they are using the local convention in the format string.
  317. if (formatString.substr(formatString.length - 2) == '/i') {
  318. if (!I18NFormatCleanRe) {
  319. I18NFormatCleanRe = new RegExp('[^\\d\\' + UtilFormat.decimalSeparator + ']','g');
  320. }
  321. formatString = formatString.substr(0, formatString.length - 2);
  322. i18n = true;
  323. hasComma = formatString.indexOf(comma) != -1;
  324. psplit = formatString.replace(I18NFormatCleanRe, '').split(dec);
  325. } else {
  326. hasComma = formatString.indexOf(',') != -1;
  327. psplit = formatString.replace(formatCleanRe, '').split('.');
  328. }
  329. if (1 &lt; psplit.length) {
  330. v = v.toFixed(psplit[1].length);
  331. } else if(2 &lt; psplit.length) {
  332. //&lt;debug&gt;
  333. Ext.Error.raise({
  334. sourceClass: &quot;Ext.util.Format&quot;,
  335. sourceMethod: &quot;number&quot;,
  336. value: v,
  337. formatString: formatString,
  338. msg: &quot;Invalid number format, should have no more than 1 decimal&quot;
  339. });
  340. //&lt;/debug&gt;
  341. } else {
  342. v = v.toFixed(0);
  343. }
  344. var fnum = v.toString();
  345. psplit = fnum.split('.');
  346. if (hasComma) {
  347. var cnum = psplit[0],
  348. parr = [],
  349. j = cnum.length,
  350. m = Math.floor(j / 3),
  351. n = cnum.length % 3 || 3,
  352. i;
  353. for (i = 0; i &lt; j; i += n) {
  354. if (i !== 0) {
  355. n = 3;
  356. }
  357. parr[parr.length] = cnum.substr(i, n);
  358. m -= 1;
  359. }
  360. fnum = parr.join(comma);
  361. if (psplit[1]) {
  362. fnum += dec + psplit[1];
  363. }
  364. } else {
  365. if (psplit[1]) {
  366. fnum = psplit[0] + dec + psplit[1];
  367. }
  368. }
  369. if (neg) {
  370. /*
  371. * Edge case. If we have a very small negative number it will get rounded to 0,
  372. * however the initial check at the top will still report as negative. Replace
  373. * everything but 1-9 and check if the string is empty to determine a 0 value.
  374. */
  375. neg = fnum.replace(/[^1-9]/g, '') !== '';
  376. }
  377. return (neg ? '-' : '') + formatString.replace(/[\d,?\.?]+/, fnum);
  378. },
  379. <span id='Ext-util-Format-method-numberRenderer'> /**
  380. </span> * Returns a number rendering function that can be reused to apply a number format multiple times efficiently
  381. * @param {String} format Any valid number format string for {@link #number}
  382. * @return {Function} The number formatting function
  383. */
  384. numberRenderer : function(format) {
  385. return function(v) {
  386. return UtilFormat.number(v, format);
  387. };
  388. },
  389. <span id='Ext-util-Format-method-plural'> /**
  390. </span> * Selectively do a plural form of a word based on a numeric value. For example, in a template,
  391. * {commentCount:plural(&quot;Comment&quot;)} would result in &quot;1 Comment&quot; if commentCount was 1 or would be &quot;x Comments&quot;
  392. * if the value is 0 or greater than 1.
  393. * @param {Number} value The value to compare against
  394. * @param {String} singular The singular form of the word
  395. * @param {String} plural (optional) The plural form of the word (defaults to the singular with an &quot;s&quot;)
  396. */
  397. plural : function(v, s, p) {
  398. return v +' ' + (v == 1 ? s : (p ? p : s+'s'));
  399. },
  400. <span id='Ext-util-Format-method-nl2br'> /**
  401. </span> * Converts newline characters to the HTML tag &amp;lt;br/&gt;
  402. * @param {String} The string value to format.
  403. * @return {String} The string with embedded &amp;lt;br/&gt; tags in place of newlines.
  404. */
  405. nl2br : function(v) {
  406. return Ext.isEmpty(v) ? '' : v.replace(nl2brRe, '&lt;br/&gt;');
  407. },
  408. <span id='Ext-util-Format-method-capitalize'> /**
  409. </span> * Alias for {@link Ext.String#capitalize}.
  410. * @method
  411. * @alias Ext.String#capitalize
  412. */
  413. capitalize: Ext.String.capitalize,
  414. <span id='Ext-util-Format-method-ellipsis'> /**
  415. </span> * Alias for {@link Ext.String#ellipsis}.
  416. * @method
  417. * @alias Ext.String#ellipsis
  418. */
  419. ellipsis: Ext.String.ellipsis,
  420. <span id='Ext-util-Format-method-format'> /**
  421. </span> * Alias for {@link Ext.String#format}.
  422. * @method
  423. * @alias Ext.String#format
  424. */
  425. format: Ext.String.format,
  426. <span id='Ext-util-Format-method-htmlDecode'> /**
  427. </span> * Alias for {@link Ext.String#htmlDecode}.
  428. * @method
  429. * @alias Ext.String#htmlDecode
  430. */
  431. htmlDecode: Ext.String.htmlDecode,
  432. <span id='Ext-util-Format-method-htmlEncode'> /**
  433. </span> * Alias for {@link Ext.String#htmlEncode}.
  434. * @method
  435. * @alias Ext.String#htmlEncode
  436. */
  437. htmlEncode: Ext.String.htmlEncode,
  438. <span id='Ext-util-Format-method-leftPad'> /**
  439. </span> * Alias for {@link Ext.String#leftPad}.
  440. * @method
  441. * @alias Ext.String#leftPad
  442. */
  443. leftPad: Ext.String.leftPad,
  444. <span id='Ext-util-Format-method-trim'> /**
  445. </span> * Alias for {@link Ext.String#trim}.
  446. * @method
  447. * @alias Ext.String#trim
  448. */
  449. trim : Ext.String.trim,
  450. <span id='Ext-util-Format-method-parseBox'> /**
  451. </span> * Parses a number or string representing margin sizes into an object. Supports CSS-style margin declarations
  452. * (e.g. 10, &quot;10&quot;, &quot;10 10&quot;, &quot;10 10 10&quot; and &quot;10 10 10 10&quot; are all valid options and would return the same result)
  453. * @param {Number/String} v The encoded margins
  454. * @return {Object} An object with margin sizes for top, right, bottom and left
  455. */
  456. parseBox : function(box) {
  457. if (Ext.isNumber(box)) {
  458. box = box.toString();
  459. }
  460. var parts = box.split(' '),
  461. ln = parts.length;
  462. if (ln == 1) {
  463. parts[1] = parts[2] = parts[3] = parts[0];
  464. }
  465. else if (ln == 2) {
  466. parts[2] = parts[0];
  467. parts[3] = parts[1];
  468. }
  469. else if (ln == 3) {
  470. parts[3] = parts[1];
  471. }
  472. return {
  473. top :parseInt(parts[0], 10) || 0,
  474. right :parseInt(parts[1], 10) || 0,
  475. bottom:parseInt(parts[2], 10) || 0,
  476. left :parseInt(parts[3], 10) || 0
  477. };
  478. },
  479. <span id='Ext-util-Format-method-escapeRegex'> /**
  480. </span> * Escapes the passed string for use in a regular expression
  481. * @param {String} str
  482. * @return {String}
  483. */
  484. escapeRegex : function(s) {
  485. return s.replace(/([\-.*+?\^${}()|\[\]\/\\])/g, &quot;\\$1&quot;);
  486. }
  487. });
  488. })();
  489. </pre>
  490. </body>
  491. </html>