This JavaScript tutorial explains how to use the string method called padEnd() with syntax and examples.
Description
In JavaScript, padEnd() is a string technique that is used to pad the quit of a string with a specific string to a certain length. This type of padding is once in a while called right pad or rpad. Because the padEnd() approach is a technique of the String object, it ought to be invoked through a precise occasion of the String class.
Syntax
In JavaScript, the syntax for the padEnd() technique is:
string.padEnd(length [, pad_string]);
Parameters or Arguments
length The favored length of the ensuing string after it has been padded. pad_string Optional. It is the special string to pad to the quit of string. If this parameter is not provided, the padEnd() approach will use a house as the pad character.
Returns
The padEnd() approach returns a string that has been padded at the cease with the precise string to the preferred length.
Note
The padEnd() technique does now not exchange the fee of the authentic 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 known as totn_string that is assigned the string price of ‘TechOnTheNet’. We have then invoked the padEnd() approach of the totn_string variable to pad the end of totn_string with ‘A’ till it is the preferred size of 20 characters.
We have written the output of the padEnd() approach to the internet browser console log, for demonstration purposes, to exhibit what the padEnd() technique returns.
The following will be output to the web browser console log:
TechOnTheNetAAAAAAAA
As you can see, the padEnd() method brought eight ‘A’ characters to the give up of ‘TechOnTheNet’ to make the ensuing string ‘TechOnTheNetAAAAAAAA’ 20 characters in length.
Specifying Multiple Characters as the Pad String
Finally, let’s see what takes place if you specify a pad_string parameter for the padEnd() approach that is multiple characters (and not simply a single character).
For example:
var totn_string = 'TechOnTheNet';
console.log(totn_string.padEnd(16,'xyz'));
The following will be output to the internet browser console log:
TechOnTheNetxyzx
In this example, we have invoked the padEnd method() with a pad_string of ‘xyz’ and a desired size of 16 characters. The padEnd() method lower back the string fee of ‘TechOnTheNetxyzx’.
Notice that the ensuing string ended with the ‘x’ persona and no longer the ‘z’ character. This took place because the sequence of characters in the pad_string persisted to repeat till the ensuing string was the preferred size of sixteen characters. In this case, it stopped repeating at the ‘x’ character.
Leave a Review