Created
January 28, 2021 13:37
-
-
Save fffiloni/e78571984fea9a7d857effa94b5bcc91 to your computer and use it in GitHub Desktop.
Add leading zero
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ES2015 | |
function zeroPad(num, places) { | |
var zero = places - num.toString().length + 1; | |
return Array(+(zero > 0 && zero)).join("0") + num; | |
} | |
zeroPad(5, 2); // "05" | |
zeroPad(5, 4); // "0005" | |
zeroPad(5, 6); // "000005" | |
zeroPad(1234, 2); // "1234" :) | |
// ES2017 | |
const zeroPad = (num, places) => String(num).padStart(places, '0') | |
console.log(zeroPad(5, 2)); // "05" | |
console.log(zeroPad(5, 4)); // "0005" | |
console.log(zeroPad(5, 6)); // "000005" | |
console.log(zeroPad(1234, 2)); // "1234" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment