simple-fmt.js 843 B

123456789101112131415161718192021222324252627282930313233
  1. // simple-fmt.js
  2. // MIT licensed, see LICENSE file
  3. // Copyright (c) 2013 Olov Lassus <olov.lassus@gmail.com>
  4. var fmt = (function() {
  5. "use strict";
  6. function fmt(str, var_args) {
  7. var args = Array.prototype.slice.call(arguments, 1);
  8. return str.replace(/\{(\d+)\}/g, function(s, match) {
  9. return (match in args ? args[match] : s);
  10. });
  11. }
  12. function obj(str, obj) {
  13. return str.replace(/\{([_$a-zA-Z0-9][_$a-zA-Z0-9]*)\}/g, function(s, match) {
  14. return (match in obj ? obj[match] : s);
  15. });
  16. }
  17. function repeat(str, n) {
  18. return (new Array(n + 1)).join(str);
  19. }
  20. fmt.fmt = fmt;
  21. fmt.obj = obj;
  22. fmt.repeat = repeat;
  23. return fmt;
  24. })();
  25. if (typeof module !== "undefined" && typeof module.exports !== "undefined") {
  26. module.exports = fmt;
  27. }