Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

String.prototype.padStart

Pads a string on the left to a given length.

Available since: ES2017

Syntax

str.padStart(targetLength, padString)

Parameters

ParameterTypeDescription
targetLengthnumberThe length to pad the string to.
padStringstringOptional. What to pad with; a space by default.

Return value

stringA new string of the required length.

Examples

A leading zero for hours and minutes:

console.log(String(5).padStart(2, '0'));
console.log(String(12).padStart(2, '0'));

Output:

05
12

The companion padEnd() pads on the right:

console.log('1'.padEnd(4, '0'));

Output:

1000

Notes

If the string is already at least the target length, it is returned unchanged. The method exists only on strings, so convert a number with String() first.

See also

Related recipes

In the tutorial

  • String methods — Useful string methods in JavaScript: finding a position, reading characters, padStart, repeat, split and join, method chains.

Thanks for reading!

Donate to the site — we work hard for you.