Posted By

jasonseney on 10/13/08


Tagged

javascript format String sprintf printf


Versions (?)

Who likes this?

5 people have marked this snippet as a favorite

jasonseney
ntulip
unnamedd
hlfcoding
guo3823538


Sprintf in Javascript (string format)


 / Published in: JavaScript
 

Example:

var result = "Hello {0}! This is {1}.".format("world","foo bar");

Returns:

"Hello World! This is foo bar."

  1. String.prototype.format = function(){
  2. var pattern = /\{\d+\}/g;
  3. var args = arguments;
  4. return this.replace(pattern, function(capture){ return args[capture.match(/\d+/)]; });
  5. }

Report this snippet  

You need to login to post a comment.