Padding a String to a Certain Length with Another String

Summary: in this tutorial, you will learn how to pad a string with another string to a certain length.

String.prototype.padStart()

The padStart() method pads a string with another string to a certain length from the start of the string and returns a resulting string that reaches a certain length. The following illustrates the padStart() method:

String.prototype.padStart(padLength [,padString]);
Code language: CSS (css)

The padStart() method takes two parameters:

  • The padLength is the length of the resulting string once it is padded. If the padLength is less than the string’s length, the string is returned as-is without padding.
  • The padString is an optional argument which is used to pad the string. The default value for this parameter is ‘ ‘. If the padString is greater than padLength, the padString will be truncated and only the left-most part will be padded.

String.prototype.padStart() examples

Suppose, you want a numeric string with 8 characters. For the string whose length is less than 8, it will be padded with zeros (0).

let str = '1234'.padStart(8,'0');
console.log(str); // "00001234"
Code language: JavaScript (javascript)

The following example pads a string by spaces because we don’t pass the pad string.

let str = 'abc'.padStart(5);
console.log(str); // "  abc" 
Code language: JavaScript (javascript)

String.prototype.padEnd()

Similar to the padStart() method, the padEnd() method pads a string to a certain length with another string. However, the padEnd() method pads from the end of the string. The following shows the syntax of the padEnd() method:

String.prototype.padEnd(padLength [,padString]);
Code language: CSS (css)

String.prototype.padEnd() examples

See the following example:

let str = 'abc'.padEnd(5);
console.log(str); // "abc  "
Code language: JavaScript (javascript)

In this example, because we did not provide the second argument, the padEnd() method uses the space ' ' to pad the 'abc' string. Here is another example:

str = 'abc'.padEnd(5,'*');
console.log(str); // "abc**"
Code language: JavaScript (javascript)

In this example, we use the * string as the second argument, the resulting string was padded by two * strings to make its length 5. And another example:

str = 'abc'.padEnd(5,'def');
console.log(str); // "abcde"
Code language: JavaScript (javascript)

In this example, the length of the resulting string must be 5, therefore, the pad string was truncated ("f") and only its left-most part ("de") was padded.

In this tutorial, you have learned how to pad a string to a certain length with another string using padStart() and padEnd() methods.

Was this tutorial helpful ?