totn JavaScript

JavaScript: String padEnd() method

This JavaScript tutorial explains how to use the string method called padEnd() with syntax and examples.

Description

In JavaScript, padEnd() is a string method that is used to pad the end of a string with a specific string to a certain length. This type of padding is sometimes called right pad or rpad. Because the padEnd() method is a method of the String object, it must be invoked through a particular instance of the String class.

Syntax

In JavaScript, the syntax for the padEnd() method is:

string.padEnd(length [, pad_string]);

Parameters or Arguments

length
The desired length of the resulting string after it has been padded.
pad_string
Optional. It is the specified string to pad to the end of string. If this parameter is not provided, the padEnd() method will use a space as the pad character.

Returns

The padEnd() method returns a string that has been padded at the end with the specified string to the desired length.

Note

  • The padEnd() method does not change the value of the original string.

Example

Let's take a look at an example of how to use the padEnd() method in JavaScript.

For example:

var totn_string = 'TechOnTheNet';

console.log(totn_string.padEnd(20,'A'));

In this example, we have declared a variable called totn_string that is assigned the string value of 'TechOnTheNet'. We have then invoked the padEnd() method of the totn_string variable to pad the end of totn_string with 'A' until it is the desired length of 20 characters.

We have written the output of the padEnd() method to the web browser console log, for demonstration purposes, to show what the padEnd() method returns.

The following will be output to the web browser console log:

TechOnTheNetAAAAAAAA

As you can see, the padEnd() method added 8 'A' characters to the end of 'TechOnTheNet' to make the resulting string 'TechOnTheNetAAAAAAAA' 20 characters in length.

Specifying Multiple Characters as the Pad String

Finally, let's see what happens if you specify a pad_string parameter for the padEnd() method that is multiple characters (and not just a single character).

For example:

var totn_string = 'TechOnTheNet';

console.log(totn_string.padEnd(16,'xyz'));

The following will be output to the web browser console log:

TechOnTheNetxyzx

In this example, we have invoked the padEnd method() with a pad_string of 'xyz' and a desired length of 16 characters. The padEnd() method returned the string value of 'TechOnTheNetxyzx'.

Notice that the resulting string ended with the 'x' character and not the 'z' character. This occurred because the sequence of characters in the pad_string continued to repeat until the resulting string was the desired length of 16 characters. In this case, it stopped repeating at the 'x' character.