Javascript String padEnd()

The padEnd() method pads the current string with another string to the end.

Example

// string definition
let string1 = "CODE";

// padding "*" to the end of the given string // until the length of final padded string reaches 10 let paddedString = string1.padEnd(10, "*");
console.log(paddedString); // Output: CODE******

padEnd() Syntax

The syntax of the padEnd() method is:

str.padEnd(targetLength, padString)

Here, str is a string.


padEnd() Parameters

The padEnd() method takes two parameters:

  • targetLength - The length of the final string after the current string has been padded.
  • padString (optional) - The string to pad the current string with. Its default value is " ".

Note:

  • If padString is too long, it will be truncated to meet targetLength.
  • For targetLength < str.length, the string is returned unmodified.

padEnd() Return Value

  • Returns a string of the specified targetLength with padString applied to the end of the current string.

Example 1: Using padEnd() Method

// string definition 
let string1 = "CODE";

// padding "$" to the end of the given string // until the length of final padded string reaches 10 let paddedString1= string1.padEnd(10, "$")
; console.log(paddedString1);

Output

CODE$$$$$$

In the above example, we have assigned a string value "CODE" to string1 and used the padEnd() method to pad "$" symbol to the end of string1. Inside the method, we have also passed 10 as targetLength.

So the method returns the final string "CODE$$$$$$" with length 10.


Example 2: Using Multiple Character padString in padEnd()

// string definition 
let string1 = "CODE";

// padding 'JavaScript' to the end of the string // until the length of padded string reaches 17 let paddedString2= string1.padEnd(17, 'JavaScript');
console.log(paddedString2);

Output

CODEJavaScriptJav

In the above example, we have passed multiple characters "JavaScript" to padEnd() and assigned the return value to paddedString2.

The method adds "JavaScript" to the end of "CODE" until the length of the final string becomes 17. So paddedString2 returns the final string "CODEJavaScriptJav" whose length is 17.


Example 3: Using a Long padString in padEnd()

The padEnd() method truncates the passed long padString to meet targetLength. For example:

// string definition 
let string1 = "CODE";

// the passed padString is truncated to meet the target length paddedString3= string1.padEnd(10, "ABCDEFGHIJKL");
console.log(paddedString3);

Output

CODEABCDEF

In the above example, we have passed "ABCDEFGHIJKL" as padString. The padEnd() method truncates the given padString so that the length of the string after padding meets the mentioned targetLength (10).

So string1.padEnd(10, "ABCDEFGHIJKL") returns the final string "CODEABCDEF" whose length equals to 10.


Recommended Reading: JavaScript String padStart()

Did you find this article helpful?