To pad a number with leading zeros, a function is created here, which checks the number with its length and add leading zeros.
Example
You can try to run the following code to pad a number with leading zeros in JavaScript −
<!DOCTYPE html> <html> <body> <script> String.prototype.padFunction = function(padStr, len) { var str = this; while (str.length < len) str = padStr + str; return str; } var str = "2"; document.write(str.padFunction("0", 4)); var str = "8"; document.write("<br>"+str.padFunction("0", 5)); </script> </body> </html>
Output
0002 00008