Skip to content

Instantly share code, notes, and snippets.

@ajalab
Created February 23, 2011 08:15
Show Gist options
  • Save ajalab/840164 to your computer and use it in GitHub Desktop.
Save ajalab/840164 to your computer and use it in GitHub Desktop.
format strings like python3
function format() {
var args, fmt, result;
args = Array.prototype.slice.apply(arguments);
fmt = this instanceof String ? this : args.shift();
if (args.length === 1 && typeof args[0] === "object") {
args = args[0];
}
result = fmt.replace(/{([^}]+)}/g, function (s, id) {
var chain = id.split("."), substr, i;
if (chain.length >= 2) {
substr = args[chain[0]];
for (i = 1; i < chain.length; i++) {
substr = substr[chain[i]];
}
} else {
substr = args[id];
}
return substr;
});
return result;
}
//String.prototype.format = format;
/*Usage:
format("pi is {0}", Math.PI);
//"pi is 3.141592653589793"
format("pi is {PI}, sqrt2 is {SQRT2}", Math);
//"pi is 3.141592653589793, sqrt2 is 1.4142135623730951"
format("pi is {0.PI}, max value is {1.MAX_VALUE}", Math, Number);
//"pi is 3.141592653589793, max value is 1.7976931348623157e+308"
format("fruits {0}, {1}, {0}!", ["apple", "lemon", "oranges"]);
//"fruits apple, lemon, apple!"
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment