Skip to main content

padStart()

padStart(str, length, padString): string

Pads the start of a string with a given character until it reaches the specified length.

DEPRECATED

Use string.padStart() directly instead.


Parametersโ€‹

str: string | null | undefinedโ€‹

The string to pad.

length: number | null | undefinedโ€‹

The target length of the padded string.

padString: string = " "โ€‹

The string to use for padding.


Returns: stringโ€‹

The padded string.


See Alsoโ€‹


Sinceโ€‹

2.0.0


Also known asโ€‹

padStart (Lodash, es-toolkit) ยท โŒ (Remeda, Radashi, Ramda, Effect, Modern Dash, Antfu)


Exampleโ€‹

// โŒ Deprecated approach
padStart('hello', 10); // => ' hello'
padStart('42', 5, '0'); // => '00042'

// โœ… Recommended approach
'hello'.padStart(10); // => ' hello'
'42'.padStart(5, '0'); // => '00042'

How it works?โ€‹

Pads the start of a string to a target length. Deprecated: Use string.padStart() directly (ES2017).

Native Equivalentโ€‹

// โŒ padStart('42', 5, '0')
// โœ… '42'.padStart(5, '0')

Use Casesโ€‹

Pad start ๐Ÿ“Œโ€‹

Pad string at start to target length.

'5'.padStart(2, '0');  // '05'

Format numbersโ€‹

Add leading zeros.

const formatted = String(num).padStart(4, '0');
// 42 โ†’ '0042'

Format time displayโ€‹

Ensure hours, minutes, and seconds always show two digits in time displays.

const formatTime = (h: number, m: number, s: number) =>
`${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;

formatTime(9, 5, 3); // '09:05:03'
formatTime(14, 30, 0); // '14:30:00'

Generate invoice numbers with leading zerosโ€‹

Format sequential IDs into fixed-width reference numbers.

const invoiceNumber = (id: number) => `INV-${String(id).padStart(6, '0')}`;

invoiceNumber(42); // 'INV-000042'
invoiceNumber(12345); // 'INV-012345'