format.js 858 B

1234567891011121314151617181920212223242526272829303132
  1. "use strict";
  2. /**
  3. * @fileOverview String helper methods
  4. *
  5. * @module strings/format
  6. */
  7. /**
  8. * Format a string quickly and easily using .net style format strings
  9. * @param {string} format A string format like "Hello {0}, now take off your {1}!"
  10. * @param {...?} args One argument per `{}` in the string, positionally replaced
  11. * @returns {string}
  12. *
  13. * @example
  14. * var strings = require("papyrus/strings");
  15. * var s = strings.format("Hello {0}", "Madame Vastra");
  16. * // s = "Hello Madame Vastra"
  17. *
  18. * @example {@lang xml}
  19. * <span>
  20. * <%= strings.format("Hello {0}", "Madame Vastra") %>
  21. * </span>
  22. */
  23. module.exports = function ( format ) {
  24. var args = Array.prototype.slice.call( arguments, 1 );
  25. return format.replace( /{(\d+)}/g, function ( match, number ) {
  26. return typeof args[number] != 'undefined'
  27. ? args[number]
  28. : match
  29. ;
  30. } );
  31. };