Zero-padded identifiers
Formatting identifiers such as invoice numbers or database keys with a consistent minimum width.
JavaScript · Function
String.prototype.padStart() adds characters to the beginning of a string until it reaches a requested length. The optional padding text is repeated or truncated as needed.
Call padStart() on a string with the desired final length and, optionally, the text used for padding. If padding is needed, the padding text is repeated and shortened as necessary, then placed before the original string; otherwise the original string is returned unchanged.
padStart(targetLength)
padStart(targetLength, padString)| Name | Type | Description |
|---|---|---|
targetLength | number | Desired length of the resulting string after padding. Values no greater than the current string length leave it unchanged. |
padString | string | Optional text used for padding; it is repeated or shortened as needed. The default is a space. |
A String of the specified targetLength with padString applied at the start.
const invoiceId = String(42).padStart(6, "0");
console.log(invoiceId); // "000042"Converts a number to text and adds leading zeroes until the text reaches six characters.
Formatting identifiers such as invoice numbers or database keys with a consistent minimum width.
Creating fixed-width labels or columns in logs and terminal output.
Ensuring displayed counters have a consistent number of visible positions.
padStart() returns a string whose length is at least the requested targetLength, adding the chosen padding at the beginning when necessary. If the original string already meets or exceeds that length, it is returned unchanged.
Follow-up: What happens when the padding text cannot fit completely? It is repeated as needed and truncated from the end so the result reaches the requested length.
The first argument is targetLength, the desired length after padding. The optional second argument is padString; if omitted, a space is used.
Follow-up: Why should a numeric value be converted first? padStart() is a String method, so String(value) or value.toString() is needed before calling it.
The method does not mutate the original string because strings are immutable. It produces and returns a new padded string when padding is required, or the original string value when no padding is needed.
Follow-up: How is an oversized padString handled? Only the portion needed to reach targetLength is retained, with truncation from the pad string's end.
String.prototype.padEnd()String.prototype.trimStart()String.prototype.repeat()String