Last active
August 29, 2015 14:04
-
-
Save thomasdarimont/05cc28366a7b806446cb to your computer and use it in GitHub Desktop.
Nice sprintf-Style placeholder replacement in format strings (only %s supported)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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