Skip to content

Instantly share code, notes, and snippets.

@thomasdarimont

thomasdarimont/format.js

Last active Aug 29, 2015
Embed
What would you like to do?
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
You can’t perform that action at this time.