stringformat.js 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. // Copyright 2008 The Closure Library Authors. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS-IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. /**
  15. * @fileoverview Implementation of sprintf-like, python-%-operator-like,
  16. * .NET-String.Format-like functionality. Uses JS string's replace method to
  17. * extract format specifiers and sends those specifiers to a handler function,
  18. * which then, based on conversion type part of the specifier, calls the
  19. * appropriate function to handle the specific conversion.
  20. * For specific functionality implemented, look at formatRe below, or look
  21. * at the tests.
  22. */
  23. goog.provide('goog.string.format');
  24. goog.require('goog.string');
  25. /**
  26. * Performs sprintf-like conversion, i.e. puts the values in a template.
  27. * DO NOT use it instead of built-in conversions in simple cases such as
  28. * 'Cost: %.2f' as it would introduce unnecessary latency opposed to
  29. * 'Cost: ' + cost.toFixed(2).
  30. * @param {string} formatString Template string containing % specifiers.
  31. * @param {...string|number} var_args Values formatString is to be filled with.
  32. * @return {string} Formatted string.
  33. */
  34. goog.string.format = function(formatString, var_args) {
  35. // Convert the arguments to an array (MDC recommended way).
  36. var args = Array.prototype.slice.call(arguments);
  37. // Try to get the template.
  38. var template = args.shift();
  39. if (typeof template == 'undefined') {
  40. throw Error('[goog.string.format] Template required');
  41. }
  42. // This re is used for matching, it also defines what is supported.
  43. var formatRe = /%([0\-\ \+]*)(\d+)?(\.(\d+))?([%sfdiu])/g;
  44. /**
  45. * Chooses which conversion function to call based on type conversion
  46. * specifier.
  47. * @param {string} match Contains the re matched string.
  48. * @param {string} flags Formatting flags.
  49. * @param {string} width Replacement string minimum width.
  50. * @param {string} dotp Matched precision including a dot.
  51. * @param {string} precision Specifies floating point precision.
  52. * @param {string} type Type conversion specifier.
  53. * @param {string} offset Matching location in the original string.
  54. * @param {string} wholeString Has the actualString being searched.
  55. * @return {string} Formatted parameter.
  56. */
  57. function replacerDemuxer(
  58. match, flags, width, dotp, precision, type, offset, wholeString) {
  59. // The % is too simple and doesn't take an argument.
  60. if (type == '%') {
  61. return '%';
  62. }
  63. // Try to get the actual value from parent function.
  64. var value = args.shift();
  65. // If we didn't get any arguments, fail.
  66. if (typeof value == 'undefined') {
  67. throw Error('[goog.string.format] Not enough arguments');
  68. }
  69. // Patch the value argument to the beginning of our type specific call.
  70. arguments[0] = value;
  71. return goog.string.format.demuxes_[type].apply(null, arguments);
  72. }
  73. return template.replace(formatRe, replacerDemuxer);
  74. };
  75. /**
  76. * Contains various conversion functions (to be filled in later on).
  77. * @private {!Object}
  78. */
  79. goog.string.format.demuxes_ = {};
  80. /**
  81. * Processes %s conversion specifier.
  82. * @param {string} value Contains the formatRe matched string.
  83. * @param {string} flags Formatting flags.
  84. * @param {string} width Replacement string minimum width.
  85. * @param {string} dotp Matched precision including a dot.
  86. * @param {string} precision Specifies floating point precision.
  87. * @param {string} type Type conversion specifier.
  88. * @param {string} offset Matching location in the original string.
  89. * @param {string} wholeString Has the actualString being searched.
  90. * @return {string} Replacement string.
  91. */
  92. goog.string.format.demuxes_['s'] = function(
  93. value, flags, width, dotp, precision, type, offset, wholeString) {
  94. var replacement = value;
  95. // If no padding is necessary we're done.
  96. // The check for '' is necessary because Firefox incorrectly provides the
  97. // empty string instead of undefined for non-participating capture groups,
  98. // and isNaN('') == false.
  99. if (isNaN(width) || width == '' || replacement.length >= Number(width)) {
  100. return replacement;
  101. }
  102. // Otherwise we should find out where to put spaces.
  103. if (flags.indexOf('-', 0) > -1) {
  104. replacement = replacement +
  105. goog.string.repeat(' ', Number(width) - replacement.length);
  106. } else {
  107. replacement = goog.string.repeat(' ', Number(width) - replacement.length) +
  108. replacement;
  109. }
  110. return replacement;
  111. };
  112. /**
  113. * Processes %f conversion specifier.
  114. * @param {string} value Contains the formatRe matched string.
  115. * @param {string} flags Formatting flags.
  116. * @param {string} width Replacement string minimum width.
  117. * @param {string} dotp Matched precision including a dot.
  118. * @param {string} precision Specifies floating point precision.
  119. * @param {string} type Type conversion specifier.
  120. * @param {string} offset Matching location in the original string.
  121. * @param {string} wholeString Has the actualString being searched.
  122. * @return {string} Replacement string.
  123. */
  124. goog.string.format.demuxes_['f'] = function(
  125. value, flags, width, dotp, precision, type, offset, wholeString) {
  126. var replacement = value.toString();
  127. // The check for '' is necessary because Firefox incorrectly provides the
  128. // empty string instead of undefined for non-participating capture groups,
  129. // and isNaN('') == false.
  130. if (!(isNaN(precision) || precision == '')) {
  131. replacement = parseFloat(value).toFixed(precision);
  132. }
  133. // Generates sign string that will be attached to the replacement.
  134. var sign;
  135. if (Number(value) < 0) {
  136. sign = '-';
  137. } else if (flags.indexOf('+') >= 0) {
  138. sign = '+';
  139. } else if (flags.indexOf(' ') >= 0) {
  140. sign = ' ';
  141. } else {
  142. sign = '';
  143. }
  144. if (Number(value) >= 0) {
  145. replacement = sign + replacement;
  146. }
  147. // If no padding is necessary we're done.
  148. if (isNaN(width) || replacement.length >= Number(width)) {
  149. return replacement;
  150. }
  151. // We need a clean signless replacement to start with
  152. replacement = isNaN(precision) ? Math.abs(Number(value)).toString() :
  153. Math.abs(Number(value)).toFixed(precision);
  154. var padCount = Number(width) - replacement.length - sign.length;
  155. // Find out which side to pad, and if it's left side, then which character to
  156. // pad, and set the sign on the left and padding in the middle.
  157. if (flags.indexOf('-', 0) >= 0) {
  158. replacement = sign + replacement + goog.string.repeat(' ', padCount);
  159. } else {
  160. // Decides which character to pad.
  161. var paddingChar = (flags.indexOf('0', 0) >= 0) ? '0' : ' ';
  162. replacement =
  163. sign + goog.string.repeat(paddingChar, padCount) + replacement;
  164. }
  165. return replacement;
  166. };
  167. /**
  168. * Processes %d conversion specifier.
  169. * @param {string} value Contains the formatRe matched string.
  170. * @param {string} flags Formatting flags.
  171. * @param {string} width Replacement string minimum width.
  172. * @param {string} dotp Matched precision including a dot.
  173. * @param {string} precision Specifies floating point precision.
  174. * @param {string} type Type conversion specifier.
  175. * @param {string} offset Matching location in the original string.
  176. * @param {string} wholeString Has the actualString being searched.
  177. * @return {string} Replacement string.
  178. */
  179. goog.string.format.demuxes_['d'] = function(
  180. value, flags, width, dotp, precision, type, offset, wholeString) {
  181. return goog.string.format.demuxes_['f'](
  182. parseInt(value, 10) /* value */, flags, width, dotp, 0 /* precision */,
  183. type, offset, wholeString);
  184. };
  185. // These are additional aliases, for integer conversion.
  186. goog.string.format.demuxes_['i'] = goog.string.format.demuxes_['d'];
  187. goog.string.format.demuxes_['u'] = goog.string.format.demuxes_['d'];