Create JS zfill property same as python zfill method

Mahabubur Rahman
0

We already know about python zfill() method and MySQL zerofill. The python zfill() and MySQL zerofill method adds zeros (0) at the beginning of the string, until it reaches the specified length. 


The problem is Java Script has no zfill property as python or MySQL.


Now we will create JS String and Number method for the same functionality. So write the bellow prototype - 


String.prototype.zfill = function (prop) {
let str = '';
if (this) {
str = this.toString()
}
return str.padStart(prop, '0')
};

Number.prototype.zfill = function (prop) {
let str = '';
if (this) {
str = this.toString()
}
return str.padStart(prop, '0')
};
Now time to test the above js method. First, we will test the number property-
 
let x = 123
x.zfill(5)
"00123"

Now check the string zfill property - 
 
let y = "10"
y.zfill(5)
"00010"

So now we can use zfill method in JS same as python.

Post a Comment

0Comments
Post a Comment (0)