JavaScript padEnd() method
The padEnd()
method in JavaScript is used to pad the current string with another string (the padString
) until the resulting string reaches the specified length (targetLength
). This method is useful for ensuring that strings have a consistent length, which can be helpful in formatting output.
Syntax:
targetLength
: The desired length of the resulting string after padding. If the length of the original string is greater than or equal to this value, the method returns the original string unchanged.padString
(optional): The string to pad the current string with. If this parameter is not provided, the default value is a space character (' '
). ThepadString
will be truncated if its length exceeds the remaining space required to reach thetargetLength
.
Return Value:
- Returns a new string that is the original string padded on the right side with the
padString
until it reaches thetargetLength
.
Example 1: Basic Usage
In this example, the string "Hello"
is padded with exclamation marks (!
) until it reaches a total length of 10 characters.
Example 2: Default Padding with Spaces
If you do not provide a padString
, the method will use a space as the default padding character.
Here, the string is padded with spaces.
Example 3: Padding with a Longer String
If the padString
is longer than the required padding, it will be truncated to fit the remaining space.
In this case, since "abc"
has a length of 3 and we need 8 more characters, it gets repeated to fill the remaining length.
Example 4: Target Length Less Than Original Length
If the original string is longer than the specified targetLength
, padEnd()
returns the original string unchanged.
Here, the original string has a length of 13, so it remains unchanged.
Example 5: Practical Use Case (Formatting Output)
You can use padEnd()
for formatting tabular data or aligning text in output.
Output:
In this example, the names are padded to a consistent length, making the output easier to read.
Summary:
- The
padEnd()
method is used to pad the end of a string with a specified string until it reaches a given length. - It takes two parameters:
targetLength
(the desired length) andpadString
(the string to pad with). - If the original string is longer than
targetLength
, it remains unchanged. - This method is useful for formatting strings, especially for creating aligned output in console applications or text displays.