Possible Duplicate:
How can I create a Zerofilled value using JavaScript?
In JavaScript, I need to have padding.
For example, if I have the number 9, it will be "0009". If I have a number of say 10, it will be "0010". Notice how it will always contain four digits.
One way to do this would be to subtract the number minus 4 to get the number of 0s I need to put.
Is there was a slicker way of doing this?
Try:
Now test:
DEMO
In ECMAScript 8 , we have new method
padStart
andpadEnd
which has below syntax.So now we can use
Since you mentioned it's always going to have a length of 4, I won't be doing any error checking to make this slick. ;)
Idea: Simply replace '0000' with number provided... Issue with that is, if
input
is 0, I need to hard-code it to return '0000'. LOL.This should be slick enough.
JSFiddler: http://jsfiddle.net/Up5Cr/
Something like that?
Bonus incomprehensible-but-slicker single-line ES6 version:
ES6isms:
let
is a block scoped variable (as opposed tovar
’s functional scoping)=>
is an arrow function that among other things replacesfunction
and is prepended by its parametersnumber =>
)return
you can omit the braces and thereturn
keyword and simply use the expressionYou could do something like this:
Edit: This was just a basic idea for a function, but to add support for larger numbers (as well as invalid input), this would probably be better:
This does 2 things:
Math.floor(num)
in place of~~num
will support larger numbers.This is not really 'slick' but it's faster to do integer operations than to do string concatenations for each padding
0
.This function is also hardcoded to your particular need (4 digit padding), so it's not generic.
Not a lot of "slick" going on so far:
When you initialize an array with a number, it creates an array with the
length
set to that value so that the array appears to contain that manyundefined
elements. Though some Array instance methods skip array elements without values,.join()
doesn't, or at least not completely; it treats them as if their value is the empty string. Thus you get a copy of the zero character (or whatever "z" is) between each of the array elements; that's why there's a+ 1
in there.Example usage: