The padStart()
method is a string method that is used to pad a string with another string. padStart()
pads the current string with another until the resulting string reaches the specified length.
// [length] = resulting string length
// [padString] = string to pad with current string
padStart([length], [padString])
[length]
: Denotes the length of the resulting string. This is the string length of the result or returned value.
[padString]
: The string that you want to use to pad the current string. [padString]
is applied to the current string from the start position. Note that this parameter is optional and the default is a space, " "
.
The return value of the padString()
method is a new string with the specified length ([length]
) that is padded with the specified pad string ([padString]
).
Let’s pad a string in an easy way. We want to pad the string "ouch"
with our pad string "O"
, the uppercase character "o"
, and a length of 7. This will result in
the new string "OOOouch"
.
// create a stringlet ourString = "ouch";// pad the stringlet paddedString = ourString.padStart(7, "O");// log the string to consoleconsole.log(paddedString); // "OOOouch"
Note: The
length
parameter should not be greater than the string length. Otherwise, it won’t be padded.
When the length
parameter is less than the string length, then no pad is added. Hence, the resulting length should be more than the current string length.
/*length parameter(2) should be greater thancurrent string length ("ish").*/console.log("ish".padStart(2, "i")) // "ish"
We can also use multiple pad characters. In the example below, we use "Ed"
to pad the string "presso"
.
// create a stringlet ourString = "presso";// pad our stringlet paddedString = ourString.padStart(8, "Ed")// log padded string to consoleconsole.log(paddedString); // "Edpresso"