Skip to content

Instantly share code, notes, and snippets.

@zo0m
Created November 20, 2014 15:38
Show Gist options
  • Save zo0m/a51acab026d86b441dad to your computer and use it in GitHub Desktop.
Save zo0m/a51acab026d86b441dad to your computer and use it in GitHub Desktop.
String.prototype.printf = function (obj) {
var useArguments = false;
var _arguments = arguments;
var i = -1;
if (typeof _arguments[0] == "string" || typeof _arguments[0] == "number") {
useArguments = true;
}
if (obj instanceof Array || useArguments) {
return this.replace(/\%([s,d])/g,
function (placeholder) {
i++;
if (useArguments) {
if (placeholder == '%s' && typeof _arguments[i] == 'string') {
return _arguments[i];
}
else if (placeholder == '%d' && typeof _arguments[i] == 'number') {
return _arguments[i];
}
else {
return JSON.stringify(_arguments[i]);
}
}
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