Last active
August 29, 2015 13:57
-
-
Save webinista/9794228 to your computer and use it in GitHub Desktop.
Add zeroes to the left of a digit. Useful for date and time applications.
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
/* | |
input = number or numeric string. | |
length = pad with zeroes until it hits this length. | |
*/ | |
function zeroPadLeft(input, length){ | |
var zero = '0', pad = '', len, padded, inp, extract; | |
/* Convert to string */ | |
inp = input+''; | |
arguments[1] ? len = arguments[1] : len = 2; | |
/* Make a negative value because we want to snip from the end. */ | |
extract = len; | |
while(len--){ | |
pad += zero; | |
} | |
padded = pad + input; | |
return padded.substr(padded.length - extract); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Changed
padded.substr(padded.length - extract);
so that it works in IE8. Subtracting the length from the padded length so the index returns that number of characters.