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
.
Method 1: Using the padStart() method: The padStart() method can be used to pad a string with the specified characters to the specified length. It takes two parameters, the target length, and the string to be replaced with. The target length is the length of resulting string after the current string has been padded.
leftPad() method to left pad a string with zeros, by adding leading zeros to string.
Calling . padStart(length) or . padEnd(length) returns a new string of the given length, with the start or end of the string padded with spaces. These padding functions do not modify the string that they are called on.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With