I am trying to create/extend the node.js util.format function so that it can be used as a prototype (e.g.: "Hello %s".format("World")). However, I have been unsuccessful trying it. I have tried the following formats to no avail:
String.prototype.format = function(){return util.format(this, arguments)};
and
String.prototype.format = function(){return util.format.apply(this, arguments)};
and also
String.prototype.format = function(args){return util.format(this, args)};
None of these work. Do you have any idea what I am doing wrong?
Thanks, Manuel
I assume you would be calling it like this?
"%s: %s".format('key', 'val');
like this:
String.prototype.format = function(){
var args = Array.prototype.slice.call(arguments);
args.unshift(this.valueOf());
return util.format.apply(util, args);
};
In your first example, you are only passing 2 arguments, the format string, and the arguments object. You get closer with your second attempt, but the context of format should probably be util. You need to add this to the set of arguments applied to format. Also when working with this on a string, you are working with the string Object, not the string literal, so you must get the literal version using valueOf.