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.


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.


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.
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses; Lead Developer, Software Architect, Product Manager, CTO and now happily a Founder.


Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.