How to add spacing or padding to the end of a string in JavaScript?

Published November 5, 2020

To add spacing or padding to the end of a string, you can use the padEnd() string method in JavaScript.

Consider this string,

// a string
const str = "Hello";

Let's add 5 spaces to the end of the string using the padEnd() string method like this,

// a string
const str = "Hello";

// add 5 spaces to the end
// of string using padEnd() method
const paddedStr = str.padEnd(10);

console.log(paddedStr); // "Hello     "

Now you might think why did we use 10 instead of 5. Because the padEnd() method starts counting characters from the start of the string. Since we already had 5 letters and passing 5 won't do the trick.

// a string
const str = "Hello";

// ❌ passing 5 won't make 5 spaces we have
// to accomodate for the whole string
const paddedStr = str.padEnd(5);

// 😕 Not what we expected
console.log(paddedStr); // "Hello"

But if you don't want to hardcode like this, there's another way to automatically pad 5 spaces to the end of the string.

It can be done using the length property of the string. First, get the length of the string then add 5 spaces like this,

// a string
const str = "Hello";

// add 5 spaces to the end
// of string using padEnd() method
const paddedStr = str.padEnd(str.length + 5);

console.log(paddedStr); // "Hello     "

Nifty Trick 🔥. Right?

You can also choose to have any string instead of spaces by passing the string as the second argument to the padEnd() method like this.

// a string
const str = "Hello";

// add 5 spaces to the end
// of string using padEnd() method
const paddedStr = str.padEnd(str.length + 5, ".");

console.log(paddedStr); // "Hello....."

See this example live in JSBin.

Key things to take away using the padEnd() string method:

  • It requires the absolute number of spaces or padding to be added to the end of the string as the first argument.
  • You can have an optional string to be used instead of spaces if provided as the second argument to the padEnd() string method.
  • the method returns a new string

Feel free to share if you found this useful 😃.


Share on: Facebook Twitter