What is the String padEnd() method in JavaScript?

The padEnd() method

The padEnd() method pads a string with another string. It does this so that the string to be padded reaches a given length.

The padding is applied to the right side of the string at its end. This is why it is also called right padding.

Syntax

The padEnd() method can be declared as shown in the code snippet below:


str.padEnd( len, pad )

Parameters

  • str: The string to be padded.

  • len: The len of str after padding it.

  • pad: The string that will be added to the end of str to pad it.

Conditions for padEnd()

  • If len is less than the length of str before padding, the padEnd() method returns str itself without padding it.

  • If the length of pad is greater than len, pad is truncated.

  • If the length of str before padding + the length of pad < len, pad is repeatedly appended at the end of str until its length becomes equal to len.

Return value

The padEnd() method returns a string of length len, which is str added with pad at the end.

Browser compatibility

The padEnd() method is supported by the following browsers:

  • Google Chrome 57
  • Firefox 48
  • Edge 15
  • Safari 10
  • Opera 44

Code

The code snippet demonstrates the use of the padEnd() method:

const str = 'Hello World!';
console.log(str.padEnd(14, 'Hi'));
console.log(str.padEnd(17, 'Hi'));
console.log(str.padEnd(12, 'Hi'));
console.log(str.padEnd(13, 'Hi'));

Explanation

  • In line 1, we declare a string, str.

  • The padEnd() method is used in lines 3, 5, 7, and 9 to pad str with the string, hi.

Free Resources