Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 767
Daniel Reis Avatar asked Dec 13 '12 12:12

Daniel Reis


People also ask

How can I pad a string to a known length?

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.

How can I pad a string with zeros on the left?

leftPad() method to left pad a string with zeros, by adding leading zeros to string.

How do you pad a string to a fixed length with spaces in JavaScript?

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.


1 Answers

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.

like image 120
Daniel Reis Avatar answered Sep 30 '22 08:09

Daniel Reis