What is padEnd() in JavaScript?

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.

Syntax

The syntax of the padEnd() method is as follows.

padEnd([length], [padString])

Parameters

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.

Return value

The padEnd() method returns a new string with a length as specified by [length] that is padded with the specified pad string [padString].

Code

The code snippet below shows how the padEnd() method works in JavaScript.

// create a string
let ourString = "Hello";
// pad the string
let paddedString = ourString.padEnd(10, "!");
// log the string to console
console.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 1010.

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 than
current 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 2020.

// create a string
let ourString = "Hello";
// pad our string
let paddedString = ourString.padEnd(20, "World")
// log padded string to console
console.log(paddedString); //

Free Resources