JavaScript String padEnd() Tutorial

In this section, we will learn what the padEnd() method is and how to use it.

JavaScript String padEnd() Method

If we want to pad the end side of a string value with other characters, we can use the padEnd() method.

JavaScript String padEnd() Syntax

padEnd(targetLength, padString)

String padEnd() Method Parameters:

The method takes two arguments:

  1. The first argument is the final length of the padded string. For example, if the string value currently has a length of 5 characters and we want to pad its end side with 3 other characters, we need to set the first argument to 8 to match the current number of characters plus 3 other pad characters.
  2. The second argument is the string value that we want to pad the target string with. This second argument is optional and, if omitted, the default value which is a white-space will be used, instead.

Note: if the length of the second argument is greater than the value specified as the first argument, then the second argument will be truncated automatically to fit the final length. Also, if the length of the second argument is less than what is needed to pad the target string, then the second argument will be repeated.

String padEnd() Method Return Value:

The return value of this method is a new string that is a combination of the original string and the characters we used to pad that original string.

Example: JavaScript right pad

const name = "John Doe";

console.log(`The length of the 'name' identifier before padding: ${name.length}`);

const rep = name.padEnd(20, "*");

console.log(`The length of the 'name' identifier after padding: ${name.length}`);

console.log(rep);

console.log(`The length of the 'rep' identifier: ${rep.length}`);

Output:

The length of the 'name' identifier before padding: 8

The length of the 'name' identifier after padding: 8

John Doe************

The length of the 'rep' identifier: 20

Example: JavaScript padding zeros

const name = "John Doe";

console.log(`The length of the 'name' identifier before padding: ${name.length}`);

const rep = name.padEnd(20, "0");

console.log(`The length of the 'name' identifier after padding: ${name.length}`);

console.log(rep);

console.log(`The length of the 'rep' identifier: ${rep.length}`);

Output:

The length of the 'name' identifier before padding: 8

The length of the 'name' identifier after padding: 8

John Doe000000000000

The length of the 'rep' identifier: 20
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies