JavaScript: 2 Ways to Format a String with Leading Zeros

Updated: June 15, 2023 By: Khue Post a comment

Padding strings with leading zeros ensures consistent formatting, proper sorting, and adherence to fixed-length requirements in numeric fields, data storage, and user interfaces.

This pithy, example-based article walks you through a couple of different ways to format a string with leading zeros in modern JavaScript.

Using the padStart() method

You can call the padStart() method on a string to add leading zeros to that string until it reaches a specified length. is simple, elegant, and built-in. It can handle any number of leading zeros and any length of the string.


string.padStart(targetLength [, padString])


  • targetLength (required): The desired length of the resulting padded string. If the original string is shorter than this length, it will be padded with the specified padString to reach the target length.
  • padString (optional): The string used for padding. It is repeated as needed to fill the padding. The default value is an empty string ("").


const s = '123'

// pad zeros on the left until the string is 5 characters
console.log(s.padStart(5, '0')) // 00123

// pad zeros on the left until the string is 10 characters
console.log(s.padStart(10, '0')) // 0000000123

// no zeros will be adde
console.log(s.padStart(3, '0')) // 123

If your input is not a string but a number, you can first convert it into a string the use the padStart() method:

const number = 2023

// convert number to string
const str = number.toString()

// pad string with 0 until its length is 10
const paddedStr = str.padStart(10, '0')
console.log(paddedStr) // 0000002023

Using a loop and string concatenation

If there’s a reason you can’t use the padStart() method, you can manually get the job done by using a loop and string concatenation. The steps are:

  1. initialize an empty string to store the leading zeros.
  2. Use a loop to count how many leading zeros are needed by subtracting the length of the input string from the target length. Inside the loop, append 0 to the leading zeros string using the += operator or the push method of an array object.
  3. Concatenate the leading zeros string with the input string using the + operator or the join() method of an array object.

Code example:

// For string
const addLeadingZeros3 = (str, totalLength) => {
  while (str.length < totalLength) {
    str = '0' + str;
  return str;

// Example usage
const str = '2023';
const paddedStr = addLeadingZeros3(str, 6);
console.log(paddedStr); // 002023

// if your input is number, the use the toString() method to convert it to string first
const num = 2024
const paddedNum = addLeadingZeros3(num.toString(), 6); // 002024

That’s it. If you have a question, feel free to leave a comment. Happy coding & enjoy your day!