0

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?

1 Answer 1

1

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.