Skip to content

Instantly share code, notes, and snippets.

@thomasdarimont
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thomasdarimont/05cc28366a7b806446cb to your computer and use it in GitHub Desktop.
Save thomasdarimont/05cc28366a7b806446cb to your computer and use it in GitHub Desktop.
Nice sprintf-Style placeholder replacement in format strings (only %s supported)
function format(format, a, b, c, d, e, f){
if (format === undefined) {
return "";
}
var idx = 0;
var args = [a, b, c, d, e, f];
return format.replace(/%s/g, function() { return args[idx++]; });
}
format("Key: %s, value: %s", "foo","bar") // "Key: foo, value: bar"
function sprintf2(){
if (arguments.length == 0) {
return "";
}
var format = arguments[0];
if (arguments.length == 1) {
return format;
}
var idx = 0;
var args = [].splice.call(arguments,1);
return format.replace(/%s/g, function() { return args[idx++]; });
}
sprintf2("Key: %s, value: %s", "foo","bar") // "Key: foo, value: bar"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment