This post will discuss how to pad a value with leading zeros in JavaScript.

There are several ways to pad a value with leading zeros in JavaScript, which means to add zeros to the start of a string or a number until it reaches a certain length. Here are some of the most common functions:

1. Using padStart() function

One way is to use the padStart() function, which is a built-in function of the string object. This function takes two arguments: the desired length of the string, and the character to use as padding. It returns a new string that is padded with the specified character at the start until it reaches the desired length. For example, we can pad a number 5 with leading zeros using padStart() like this:

Download  Run Code

 
This function is useful if we want a simple and fast way to format numbers with leading zeros. However, it will not work for negative numbers and with old browsers. Also, if the original string is longer than the target length, it is returned unchanged.

2. Using slice() function

Another way is to use the slice() function, which is also a built-in function of the string object. It takes one or two arguments: the start index and the end index of the substring to return, and returns a new string that is a part of the original string between the specified indexes. We can use it to pad a number with leading zeros by adding a string of zeros before the number and slicing it from the end. For example, using the same number as before, we can format it with leading zeros using slice() like this:

Download  Run Code

 
We can use the repeat() to generate the sequence of repeated zeros. The repeat() function takes a number as an argument and returns a new string that contains the original string repeated that many times.

Download  Run Code

 
This option achieves the same result as the padStart() function, but it may not work for negative numbers or numbers longer than the padding length.

3. Using a custom function

A third way is to write our own function to pad a value with leading zeros by using our own logic. It is useful if we want more control and flexibility over how to pad numbers with leading zeros. However, it may result in more code and complexity than the other options. For example, we can format a number with leading zeros using a custom function like this:

Download  Run Code

That’s all about padding a value with leading zeros in JavaScript.