Created
June 8, 2011 02:56
-
-
Save nzakas/1013686 to your computer and use it in GitHub Desktop.
Quick and dirty sprintf
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
/* | |
* 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." | |
*/ |
I like it!
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
sprintf('hi%s') will output 'hiundefined'
It remains quick and dirty :D