Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท String

String.prototype.padStart()

Reference for JavaScript String.prototype.padStart(): pad the start of a string to a fixed length, add leading zeros, format times and mask card numbers.

The padStart() method extends a string to a target length by adding padding at the beginning. If the string is already long enough, it comes back unchanged.

Its best-known job is adding leading zeros to numbers, such as 07 for a month or 00ff for a hex value. It is also handy for right-aligning columns and for masking all but the last few characters of a value.

JavaScript
"7".padStart(3, "0"); // "007"

Try it

JS Leading zeros

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Masking and pad string rules

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
string.padStart(targetLength)
string.padStart(targetLength, padString)
Name Description
targetLength The length the result should have. If it is not greater than the string's length, nothing is added. It is converted to an integer.
padString Optional. The text used for padding. It is repeated and cut as needed. Defaults to a single space. An empty string adds nothing.

Return value: a new string of at least targetLength code units with padding at the start, or the original string if no padding applies.

Exceptions: none for ordinary values. An enormous targetLength can throw a RangeError.

Usage notes

  • The target is the final length. "abc".padStart(10, "12345") returns 1234512abc: seven pad characters are added, and the pad string is cut at the end of its last repetition.
  • Numbers are not strings. Convert with String(n) or a template literal first; (7).padStart does not exist.
  • Negative numbers. String(-5).padStart(3, "0") gives 0-5, because the minus sign is just another character. Format the sign separately, or use Intl.NumberFormat with minimumIntegerDigits.
  • It never truncates. A longer string is returned as it is. Use slice() to cut first.
  • Code units, not glyphs. Lengths count UTF-16 code units, so emoji and combining marks affect alignment.
  • Dates: for padded date parts, padStart(2, "0") is the usual tool; for full date formatting prefer Intl.DateTimeFormat.
  • Not a security measure. Masking for display is fine, but do not rely on it to protect data that is still present in the page or in logs.
  • End instead of start: see padEnd().

Browser support

padStart() was added in ES2017 and works in all current browsers.