javascript example - Add padding/leading zero to a number of astring in typescript


In this blog post, Let’s see an example of add pad zeros to the number/strings with 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 you are migrating blog to hugo, or other providers URL need 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 makes 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 new 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 of the string, This is optional, default is empty 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  

Similar Posts