I’m using this prototype to format strings in javascript:
String.prototype.format = function () {
var args = arguments;
return this.replace(/{(\d+)}/g, function (match, number) {
return typeof args[number] != 'undefined'
? args[number]
: match
;
});
};
While it works fine, It doesn’t do all I would like to do. If I have a string that is supposed to be formatted as {0:000000}, this will not fix it.
How can I extend this, to add the extra 0’s to my string?
I can easily detect them, by fixing the regexp, but how do I format the return correctly?
Calling
toFixed( )on a float will round/pad it accordingly if that helps?So you can check for a float in the same way you check it’s not undefined. If you’ve got one, you do
args[number].toFixed(6).You could also build in additional flexibility by extending your regex to parse your template to function similarly to python (e.g. ‘{.3f}’ for 3 d.p)