Little tricks: string padding in Javascript

I just found this little trick to zero pad numbers in Javascript. It is also applicable to padding with any character, not just zeros.

var n = 123
String("00000" + n).slice(-5); // returns 00123
("00000" + n).slice(-5); // returns 00123
("     " + n).slice(-5); // returns "  123" (with two spaces)

Found here.

9 thoughts on “Little tricks: string padding in Javascript

  1. Pingback: Truco Manso: rellenar con ceros un nĂºmero en javascript » Codigo Manso

  2. lerele

    Here is an extension:

    String.prototype.padding = function(padchar,length){
    return String(padchar.times(length) + this.toString()).slice(-length);
    };

    Usage: ’1234′.padding(’0′,6); //returns ’001234′

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Additional comments powered by BackType