What is the String.padStart() method in JavaScript?

The padStart() method pads a string with another string so that the string to be padded reaches a given length. Since the padding is applied to the left of the string as its starts, it is also called left padding.

Syntax

The padStart() method can be declared as shown in the code snippet below.

str.padStart( len, pad )

Parameters

  • str: The string to be padded.
  • len: The length of str after padding it.
  • pad: The string that will be added to the start of str to pad it.
  • If len is less than the length of str’ before padding, the padStart() method returns str itself without padding it.
  • If the length of pad is greater than len, pad is truncated.
  • If the length of str before padding and the length of pad is greater than len, pad is repeatedly appended at the start of str. This is done until its length becomes equal to len.

Return value

The padStart() method returns a string of the length of len, which is str added with pad at the start.

Browser compatibility

The padStart() method is supported by the following browsers:

  • Google Chrome 57
  • Firefox 48
  • Edge 15
  • Safari 10
  • Opera 44

Code

The code snippet below demonstrates the use of the padStart() method.

const str = 'Hello World!';
console.log(str.padStart(14, 'Hi'));
console.log(str.padStart(17, 'Hi'));
console.log(str.padStart(12, 'Hi'));
console.log(str.padStart(13, 'Hi'));

Explanation

  • In line 1, we declare a string, str.
  • The padStart() method is used in lines 3,5,7 and 9 to pad str with the string, hi.

Free Resources