String Padding: Learn padStart() and padEnd()
Sometimes, we need to adjust the length of a string by adding characters to its beginning or end.
This is where padStart()
and padEnd()
come into play.
Let's learn how to use these two handy methods.
padStart()
What does it do?
padStart()
adds characters to the beginning of a string until it reaches a specified length.
How to
const str = "5"; const paddedStr = str.padStart(3, "0"); console.log(paddedStr); // 👉 Outputs: "005"
In this example, we wanted our string to be 3 characters long. Since our original string was only 1 character, padStart()
added two "0" characters to the beginning.
padEnd()
What does it do?
padEnd()
is the counterpart to padStart()
. It adds characters to the end of a string until it reaches a specified length.
How to
const str = “hello"; const paddedStr = str.padEnd(8, "."); console.log(paddedStr); // 👉 Outputs: “hello..."
Here, we wanted our string to be 8 characters long. Our original string was 5 characters, so padEnd()
added three "." characters to the end.
Notes to remember
- If the string is already longer than the specified length, these methods won't trim it. They'll return the original string.
- If you don't provide a padding character, both methods will use a space by default.
- If the padding string is too long, it will be sliced to fit the desired length.