References

Beginner-friendly references for web development, with live, editable examples.

The JavaScript string.padStart() method

Method JavaScript All modern browsers Updated
Quick answer

The padStart() method adds characters to the front of a string until it reaches a target length, then returns the result. "5".padStart(2, "0") gives "05". It's the clean way to zero-pad numbers, align text or format times. Its mirror, padEnd(), pads the end instead.

Overview

padStart() makes a string a certain minimum length by adding padding to the beginning. You give it the target length and, optionally, what to pad with (a space by default). If the string is already that long or longer, it's returned unchanged.

The textbook use is zero-padding numbers for display: "7".padStart(2, "0") gives "07", perfect for clocks, dates and invoice numbers. It's also handy for right-aligning short labels in monospaced output. Because numbers don't have these methods, you'll often call String(n).padStart(...) or pad after a toFixed().

Its counterpart padEnd() adds the padding to the end instead — useful for left-aligning columns. Both return a new string and leave the original alone. The pad string repeats as needed and is truncated if it would overshoot the target length.

Syntax

const padded = str.padStart(targetLength)
const padded = str.padStart(targetLength, padString)

"5".padStart(2, "0")   // "05"
"42".padStart(5, "*")  // "***42"

Parameters

The string.padStart() method accepts the following parameters.

Parameter Description
targetLength The length the result should reach. If the string is already this long, it is returned unchanged.
padString Optional. The text to pad with, repeated as needed. Defaults to a space (" ").

Example

Live example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
  const h = 9, m = 5;

  const time =
    String(h).padStart(2, '0') + ':' +
    String(m).padStart(2, '0');

  document.getElementById('out').textContent = time; // 09:05
</script>

Best practices

  • Zero-pad numbers for display with String(n).padStart(2, "0").
  • Use padEnd() instead when you want to pad (and align) on the right.
  • Convert numbers to strings first — numbers have no padStart().
  • Remember a string already at or above the target length comes back unchanged.

Frequently asked questions

How do I add a leading zero to a number in JavaScript?
Convert to a string and pad: String(7).padStart(2, "0") gives "07".
What is the difference between padStart() and padEnd()?
padStart() adds padding to the front; padEnd() adds it to the end. Use padStart() to right-align, padEnd() to left-align.
What does padStart() do if the string is already long enough?
It returns the string unchanged — padding only fills up to the target length.
Can I pad with more than one character?
Yes. The pad string repeats as needed: "42".padStart(6, "ab") gives "abab42".