javascript example Add padding, leading zero to a different types

This tutorial shows how to add leading zero to the different object in javascript.

  • add leading zeroes to date month
  • using padStart() method in ES08
  • pad zero to string in javascript

You can check my other post on Javascript check substring exists in a String

Add leading zero to the month of date object in javascript

Blog URLS contains 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.

To format the month, Check if month is less than 10, add leading zero, else return it.

var date = new Date();
console.log(date); //2020-03-18T15:16:08.699Z
const month=date.getMonth() + 1
console.log(month); //3
const monthOutput = month < 10 ? `0${month}` : `${month}`;
console.log(monthOutput); //03


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