Javascript – Padding zero to the left of number in Javascript

javascript

I have a ten digit number that will always be constant. I want to pad it so, that it will always remove a zero for every extra number added to the number. Can someone please show me an example of how I can do this?

eg. 0000000001

0000000123 
0000011299

Best Solution

You can use this function:

function pad (str, max) {
  str = str.toString();
  return str.length < max ? pad("0" + str, max) : str;
}

Output

pad("123", 10);    // => "0000000123"

JSFIDDLE DEMO