How to pad a number with leading zeros in JavaScript?

JavascriptWeb DevelopmentFront End Technology

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 −

Live Demo

<!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
raja
Published on 03-Feb-2018 13:04:25
Advertisements