javascript Add padding,leading zero to a string number

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

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

Add leading zero to the month of date object in javascript

IN blog URL, default post URL is year/month/postname ie 2020/02/my-postname.
Suppose Date object in javascript, getMonth return 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 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  
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  

Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
You'll get a notification every time a post gets published here.