Simplest inline method to left pad a string [duplicate]
Possible Duplicate:
Is there a JavaScript function that can pad a string to get to a determined length?
What's the simplest way to left pad a string in javascript?
I'm looking for an inline expression equivalent to mystr.lpad("0", 4)
: for mystr='45'
would return 0045
.
Found a simple one line solution:
("0000" + n).slice(-4)
If the string and padding are in variables, you would have:
mystr = '45'
pad = '0000'
(pad + mystr).slice(-pad.length)
Answer found here, thanks to @dani-p. Credits to @profitehlolz.
function pad(value, length) {
return (value.toString().length < length) ? pad("0"+value, length):value;
}