Skip to content

Instantly share code, notes, and snippets.

@ksuzushima
Created April 26, 2018 02:01
Show Gist options
  • Save ksuzushima/1b1c5d79cf198595376bebdb7547e35a to your computer and use it in GitHub Desktop.
Save ksuzushima/1b1c5d79cf198595376bebdb7547e35a to your computer and use it in GitHub Desktop.
Zero Padding in JavaScript
function zeroPadding(number, length) {
return (Array(length).join('0') + number).slice(-length);
}
zeroPadding(240, 10) // 0000000240
/**
* String.prototype.padStart()
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
*/
const str = 'abc';
str.padStart(10); // " abc"
str.padStart(10, "foo"); // "foofoofabc"
str.padStart(6,"123465"); // "123abc"
str.padStart(8, "0"); // "00000abc"
str.padStart(1); // "abc"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment