The padStart() method adds another string to the beginning of the current string (multiple times, if necessary) until the resulting string reaches the given length.
Pad a number with Leading Zeros in JavaScript
To pad leading zeros to a number:
- To pad a string with leading zeros, use the padStart() method.
- The padstart() method will add zeros to the start of the string until it reaches the specified target length.
Example –
function padWithZero(num, targetLength) {
return String(num).padStart(targetLength, '0');
}
const num = 5;
// pad number with 2 leading zeros
console.log(padWithZero(num, String(num).length + 2));
// pad number with 3 leading zeros
console.log(padWithZero(num, String(num).length + 3));
// pad number with 4 leading zeros
console.log(padWithZero(num, String(num).length + 4));
Explanation –
We created a function padWithZero
() that can be used to pad a number with leading zeros.
To pad the start of a string, pass two parameters to the padStart
method:
- The target length is the desired length of the string that the
padStart
method should return. This method will add padding to the start of the string until the desired length is reached. - To pad a string with another string, we supply the string we want to pad our existing string with as the pad string argument.
If you have a string of length 2 and want to increase the string to a target length of 4, then you need to add 2 leading zeros to the string.
console.log(String(22).padStart(4, '0'));
The padStart method returns a string. If you convert the result back to a number, the leading zeros will be dropped.
function padWithZero(num, targetLength) {
return String(num).padStart(targetLength, '0')
}
console.log(Number(padWithZero(5, 10)));