Add Leading Zeros to a String in JavaScript

avatar

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.

index.js
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.

index.js
console.log('22'.padStart(4, '0')); // ๐Ÿ‘‰๏ธ 0022

Here are some more examples of using the padStart method.

index.js
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.

index.js
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 #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee