JavaScript padStart() method
The padStart()
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 helpful for ensuring that strings have a consistent length, particularly for formatting output or aligning text.
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 left side with the
padString
until it reaches thetargetLength
.
Example 1: Basic Usage
In this example, the string "World"
is padded with "Hello "
on the left side 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 to the left.
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, the string "42"
is padded with zeros until it reaches a total length of 5 characters.
Example 4: Target Length Less Than Original Length
If the original string is longer than the specified targetLength
, padStart()
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 padStart()
for formatting tabular data or aligning text in output.
Output:
In this example, the IDs are padded to a consistent length on the left, and the names are padded to a consistent length on the right, making the output easier to read.
Summary:
- The
padStart()
method is used to pad the start 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.