How to Pad Strings in Javascript

javascript
Published on January 25, 2019

Sometimes it is required to make sure that a string is of a specific length :

  • If the length is less than the specified length, then you need some extra characters towards the beginning or end. Extra characters may be spaces, dots or something else.
  • If the length is greater than the specified length, then you need to leave the string as it is.

You can achieve such a requirement with the native Javascript methods — padStart and padEnd.

Padding from the Beginning with padStart

The padStart method pads the target string with another string until a specific length is reached for the target. As the name tells, padding is added from the beginning, or left side of the target. It accepts two parameters :

  1. targetLength : The required length of the target string
  2. padString : The string that is used as the padding. If this padding string is too long and target length has been achieved, it will be truncated from the right.
    This parameter is optional. The default value is the space character " "
var str = "I am John";

// outputs "      I am John" 
str.padStart(15);

// outputs "......I am John" 
str.padStart(15, '.');

// outputs "xyzxyzI am John" 
str.padStart(15, 'xyz');

// outputs "I am John" 
str.padStart(5, '.');

// outputs "123456I am John"
// 789 is truncated as target length is achieved
str.padStart(15, '123456789');

Padding from the End with padEnd

The padEnd method pads the target string with another string from the right side until a specific length is reached for the target. It also accepts two parameters :

  1. targetLength : Length of the target string
  2. padString : The string that is used as the padding. If target length has been achieved, this padding string will be shortened from the right side.
    This is optional and the default value is space " "
var str = "I am John";

// outputs "I am John      " 
str.padEnd(15);

// outputs "I am John......" 
str.padEnd(15, '.');

// outputs "I am Johnxyzxyz" 
str.padEnd(15, 'xyz');

// outputs "I am John" 
str.padEnd(5, '.');

// outputs "I am John123456"
// 789 will be removed
str.padEnd(15, '123456789');
In this Tutorial