Skip to content

Instantly share code, notes, and snippets.

@nzakas
Created June 8, 2011 02:56
Show Gist options
  • Save nzakas/1013686 to your computer and use it in GitHub Desktop.
Save nzakas/1013686 to your computer and use it in GitHub Desktop.
Quick and dirty sprintf
/*
* Quick and Dirty sprintf
* Copyright 2011 Nicholas C. Zakas. All rights reserved.
* BSD licensed
*/
/*
* This function does not attempt to implement all of sprintf, just %s,
* which is the only one that I ever use.
*/
function sprintf(text){
var i=1, args=arguments;
return text.replace(/%s/g, function(pattern){
return (i < args.length) ? args[i++] : "";
});
}
/*
* Usage:
* var result = sprintf("Hello %s, what a nice %s it is.", "world", "day");
* console.log(result); //"Hello world, what a nice day it is."
*/
@yuanchuan
Copy link

sprintf('hi%s') will output 'hiundefined'

 return args[i++] || '';

It remains quick and dirty :D

@nzakas
Copy link
Author

nzakas commented Jun 8, 2011

I like it!

@ryanseddon
Copy link

console.log/warn/info already has string formatting built in, but this is handy to add it to browsers that don't.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment