javascript Add padding, leading zero to a string number

In this blog post, Let’s see an example of adding pad zeros to the number/strings with the below examples.

Add leading zero to the month of date object in javascript

In the blog URL, the default post URL is year/month/postname ie 2020/02/my-postname.
Suppose the Date object in javascript, getMonth return the number as 3 instead of 03.

When migrating the blog to Hugo, or other providers URL needs to change the month from 3 to 03 as seen below.

var date = new Date();
console.log(date); //2020-03-18T15:16:08.699Z

console.log(date.getMonth() + 1); //3

Appending zero string to the given number or a string

Add the month object with a zero string to make the beginning of a number.

var date = new Date();
console.log(date); //2020-03-18T15:16:08.699Z
let month = date.getMonth() + 1;
console.log(month); //3

stringMonth = "0" + month;
console.log(stringMonth); //03

padStart method ES2017 method

padStart method is a method introduced to String objects in ES08. Here is a syntax for it

string.padStart(outputstringlength,padding value

Accepted parameters
outputstringlength - output length string
padding value - adding value to start the string, It is optional, default is space Return type - padded the given string with padding value and output is a string of length given.

const strNumber = "9";
console.log(strNumber.padStart(2, "0")); // 09