Add Leading Zeros to a String in JavaScript


Borislav Hadzhiev

Sat Oct 23 20212 min read

Add Leading Zeros to a String #

Use the padStart() method to add leading zeros to a string. The method allows us to pad the current string with zeros to a specified target length and returns the result.

function addLeadingZeros(str, targetLength) { return str.padStart(targetLength, '0'); } const str = '53'; console.log(addLeadingZeros(str, 3)); // 053 console.log(addLeadingZeros(str, 4)); // 0053 console.log(addLeadingZeros(str, 5)); // 00053

We used the padStart method to add leading zeros to a string.

We passed the following 2 parameters to the padStart method:

  1. target length - the length of the string the padStart method should return, once it has been padded.
  2. pad string - the string we want to pad our existing string with, in our case - 0.

An easy way to think about the method is - it pads the original string to a target length with a supplied string.

If you have a string of length 2 and you set the target length to 4, the string will get padded with 2 characters.

console.log('22'.padStart(4, '0')); // 👉️ 0022

Here are some more examples of using the padStart method.

console.log('hello'.padStart(8)); // 👉️ " hello" console.log('hello'.padStart(8, '0')); // 👉️ "000hello" console.log('hello'.padStart(1)); // 👉️ "hello"

In our last example, we provided target length of 1, which is less than the string's length. In this scenario, the method returns the string as is.

If the length of the pad string + the length of the original string exceed the specified target lenth, the pad string gets truncated.

console.log('22'.padStart(4, '01234567')); // 👉️ 0122

Our string has a length of 2 and we specified a target length of 4, so only 2 of characters from the pad string were prepended to the string.

Further Reading #

Use the search field on my Home Page to filter through my more than 1,000 articles.