The padEnd() method of the String class in JavaScript pads the current string with another string (repeated, if needed) so that the resulting string reaches a given length. The padding is applied from the end (right) of the current string.
There are 2 variations for the syntax of String.padEnd() method. They are:
padEnd(targetLength)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
targetLength | required | The length of the resulting string once the current string has been padded. If this parameter is smaller than the current string's length, the current string is returned as it is. |
This method pads the current string with spaces from the end to reach the target length.
Returns value of type String
.
padEnd(targetLength, padString)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
targetLength | required | The length of the resulting string once the current string has been padded. If this parameter is smaller than the current string's length, the current string is returned as it is. |
padString | optional | The string to pad the current string with. If this string is too long, it will be truncated to the required length. The default value is a space (' '). |
This method pads the current string with the specified padString from the end to reach the target length.
Returns value of type String
.
In JavaScript, we can use the padEnd()
method to pad a string with spaces from the end to reach the specified target length.
For example,
str
with the value 'Hello'
.padEnd()
method with the target length 10
.paddedStr
.paddedStr
to the console using console.log()
method.const str = 'Hello';
const paddedStr = str.padEnd(10);
console.log(paddedStr);
'Hello '
In this example, we use the padEnd()
method to pad a string with a specified string from the end to reach the target length.
For example,
str
with the value 'Hello'
.padEnd()
method with the target length 10
and the pad string '123'
.paddedStr
.paddedStr
to the console using console.log()
method.const str = 'Hello';
const paddedStr = str.padEnd(10, '123');
console.log(paddedStr);
'Hello12312'
In this example, we use the padEnd()
method with a target length that is less than the string's length, resulting in the original string being returned.
For example,
str
with the value 'Hello World'
.padEnd()
method with the target length 5
.paddedStr
.paddedStr
to the console using console.log()
method.const str = 'Hello World';
const paddedStr = str.padEnd(5);
console.log(paddedStr);
'Hello World'
In this JavaScript tutorial, we learned about padEnd() method of String: the syntax and few working examples with output and detailed explanation for each example.