JavaScriptStrings

String.prototype.padStart()

Pads a string on the left with the given text until it reaches the specified length. Perfect for leading zeros.

Returns
A new string at least targetLength long, padded on the left.
Changes the original
No
On this page

Example

#
JavaScript
const minutes = 5
const seconds = 9

const time = `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`
console.log(time)
console.log('42'.padStart(6, '0'))
Console
05:09
000042

Definition and usage

#

The padStart() method adds characters to the start of a string until it reaches the desired length. By default it pads with spaces, but you can supply your own text, such as "0". If the string is already long enough, it comes back unchanged.

It is most often used to format numbers: minutes and seconds (05:09), order numbers with leading zeros, or right-aligning columns of text. Convert the number to a string first, for example with String(n), since padStart() is a string method.

When the padding text is longer than needed, it gets trimmed down. The original does not change; the method returns a new string.

Syntax

#
Syntax
string.padStart(targetLength)
string.padStart(targetLength, padString)

Parameters

#
  • targetLength

    number

    The target length of the result. If it is less than or equal to the string's length, the string comes back unchanged.
  • padString

    string, optional

    The text used for padding, repeated and trimmed as needed. Defaults to a space.

More examples

#
Right-aligning numbers
JavaScript
const scores = [
  ['Mia', 1200],
  ['Jack', 85],
  ['Eva', 430]
]

for (const [name, points] of scores) {
  console.log(name.padEnd(6) + String(points).padStart(5))
}
Console
Mia 1200
Jack 85
Eva 430
Masking and trimming the padding
JavaScript
console.log('4815'.padStart(12, '*'))
console.log('7'.padStart(4, 'ab'))
console.log('Long text'.padStart(3))
Console
********4815
aba7
Long text

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • padStart() works on strings. For a number, write String(n).padStart(2, "0"), because calling it directly on a number throws a TypeError.
  • For formatting dates and times according to locale conventions, also consider Intl.DateTimeFormat, which adds leading zeros on its own.

Related entries

#

Spotted a mistake or missing an example? Write to us.