d
Amit DhamuSoftware Engineer
 

Leading zeros with padStart

1 minute read 00000 views

Sometimes, you might want to utilise an effect where you prefix zeroes (or any number) to a string. An example would be something like a hit counter.

We can achieve this using padStart

const withLeadingZeroes = (value, numberOfZeroes) =>
  String(value).padStart(numberOfZeroes, '0')

console.log(withLeadingZeroes(1, 5))
// > 00001

console.log(withLeadingZeroes(23, 5))
// > 00023

console.log(withLeadingZeroes(75923, 5))
// > 75923

console.log(withLeadingZeroes(1067594, 5))
// > 1067594

Keep in mind that if the value you pass to withLeadingZeroes has more digits than the numberOfZeroes argument, the effect won't be seen as the last example above shows.

The same effect can also be achieved in PHP.