Skip to content

Instantly share code, notes, and snippets.

@jjt
Created March 1, 2011 22:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jjt/850046 to your computer and use it in GitHub Desktop.
Save jjt/850046 to your computer and use it in GitHub Desktop.
String.printf.js (Credits go to http://daviddahl.blogspot.com)
// "%s is great".printf('This')
// -> This is great
//
// "{bar} or {foo}".printf({foo:'A',bar,'B'})
// -> B or A
//
// "{}, {}, {}!".printf([1,2,3])
// -> 1, 2, 3!
String.prototype.printf = function (obj) {
var useArguments = false;
var _arguments = arguments;
var i = -1;
if (typeof _arguments[0] == "string") {
useArguments = true;
}
if (obj instanceof Array || useArguments) {
return this.replace(/\%s/g,
function (a, b) {
i++;
if (useArguments) {
if (typeof _arguments[i] == 'string') {
return _arguments[i];
}
else {
throw new Error("Arguments element is an invalid type");
}
}
return obj[i];
});
}
else {
return this.replace(/{([^{}]*)}/g,
function (a, b) {
var r = obj[b];
return typeof r === 'string' || typeof r === 'number' ? r : a;
});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment