Skip to content

Instantly share code, notes, and snippets.

@webinista
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save webinista/9794228 to your computer and use it in GitHub Desktop.
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.
/*
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);
}
@webinista
Copy link
Author

Wonky in < IE8. Working on a refinement.

@webinista
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment