Javascript String.format()
A cheap implementation that supports basic escaping and abuses JavaScript's duck typing
by Braden Best
HTML
<textarea id=txt></textarea>
CSS
#txt{
width:100%;
height:25em;
background:inherit;
border:none;
}
JavaScript
if(!String.format){
String.format = function(){
var argv = Array.prototype.slice.call(arguments),
string = argv[0],
i = 0;
string = string.replace("%%", "<<percent>>", "g");
while(argv[i++]){
string = string.replace(/%[a-z]/, argv[i]);
}
string = string.replace("<<percent>>", "%", "g");
return string;
}
}
txt.value = String.format(
"Hello %s!\n" +
"The answer to %s is %d.\n" +
"Here's an array: %a\n" +
"Here's a percentage sign: %%\n" +
"Here's a percentage sign and the letter d: %d\n" +
"Here it is again but escaped properly: %%d\n" +
"Here's the format string itself, just to go extra-meta:\n\n" +
"Hello %%s!\\nThe answer to %%s is %%d\\nHere's an array: %%a\\nHere's a percentage sign: %%%%\\nHere's a percentage sign and the letter d: %%d\\nHere it is again but escaped properly: %%%%d\\nHere's the format string itself, just kidding.",
"world",
"Life, the Universe, and Everything",
42,
[1,2,3,4,5]);