Skip to content

Instantly share code, notes, and snippets.

@fffiloni
Created January 28, 2021 13:37
Show Gist options
  • Save fffiloni/e78571984fea9a7d857effa94b5bcc91 to your computer and use it in GitHub Desktop.
Save fffiloni/e78571984fea9a7d857effa94b5bcc91 to your computer and use it in GitHub Desktop.
Add leading zero
// 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