The padEnd()
method in JavaScript is used to pad a string from the end with another string. padEnd()
pads the current string multiple times until it reaches a specified length.
The syntax of the padEnd()
method is as follows.
padEnd([length], [padString])
The padEnd()
method takes the following parameters:
[length]
: The desired length of the string to return.
[padString]
: The string that you want to use to pad the current string. [padString]
is applied to the current string from the end position.
Note that this parameter is optional and has a default value of the space character,
" "
.
The
length
parameter should not be greater than the string length. Otherwise, it won’t be padded.
The padEnd()
method returns a new string with a length as specified by [length]
that is padded with the specified pad string [padString]
.
The code snippet below shows how the padEnd()
method works in JavaScript.
// create a stringlet ourString = "Hello";// pad the stringlet paddedString = ourString.padEnd(10, "!");// log the string to consoleconsole.log(paddedString); // Padded string with length 10
In the code snippet above, the padEnd()
method is used to pad the string "Hello"
with the string "!"
. The total length of the returned string is .
When the length
parameter is less than the string length, then no padding will be added, as shown below.
/*length parameter(2) should be greater thancurrent string length ("ish").*/console.log("wow".padEnd(2, "w")) // "ish"
A string can also be padded with multiple characters. The code below pads the string "Hello"
with the string "World"
until the length reaches .
// create a stringlet ourString = "Hello";// pad our stringlet paddedString = ourString.padEnd(20, "World")// log padded string to consoleconsole.log(paddedString); //