having fun with code

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.

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

Found here.

Related Posts:

2 Comments to Little tricks: string padding in Javascript

  1. July 27, 2010 at 07:18 | Permalink

    Wow!! Amazing solution! Simple and clean!

  2. Firnaz's Gravatar Firnaz
    July 7, 2011 at 02:26 | Permalink

    Thanks. So helpful

  1. By on July 30, 2010 at 09:08

Leave a Reply

You can 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

About the blog

This is a blog about development, focused mainly on Javascript but also other languages like python, shell scripts and more.

About the author

Eneko Alonso is a software engineer and UI developer with more than eight years of experience in software and web development. He lives in San Luis Obispo, California and works at LEVEL Studios.

Contact Info

Contact Info

PromoteJS

JavaScript JS Documentation