I\'m looking for a good JavaScript equivalent of the C/PHP printf()
or for C#/Java programmers, String.Format()
(IFormatProvider
for .
I have a solution very close to Peter's, but it deals with number and object case.
if (!String.prototype.format) {
String.prototype.format = function() {
var args;
args = arguments;
if (args.length === 1 && args[0] !== null && typeof args[0] === 'object') {
args = args[0];
}
return this.replace(/{([^}]*)}/g, function(match, key) {
return (typeof args[key] !== "undefined" ? args[key] : match);
});
};
}
Maybe it could be even better to deal with the all deeps cases, but for my needs this is just fine.
"This is an example from {name}".format({name:"Blaine"});
"This is an example from {0}".format("Blaine");
PS: This function is very cool if you are using translations in templates frameworks like AngularJS:
{{('hello-message'|translate).format(user)}}
{{('hello-by-name'|translate).format( user ? user.name : 'You' )}}
Where the en.json is something like
{
"hello-message": "Hello {name}, welcome.",
"hello-by-name": "Hello {0}, welcome."
}