Python like string formatting in javascript


/ Published in: JavaScript
Save to your folder(s)



Copy this code and paste it in your HTML
  1. /* Python(ish) string formatting:
  2.   * >>> format('{0}', ['zzz'])
  3.   * "zzz"
  4.   * >>> format('{x}', {x: 1})
  5.   * "1"
  6.   */
  7. function format(s, args) {
  8. var re = /\{([^}]+)\}/g;
  9. return s.replace(re, function(_, match){ return args[match]; });
  10. }

URL: http://davedash.com/2010/11/19/pythonic-string-formatting-in-javascript/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.