Padding Methods
padStart(targetLength, padString) adds padString to the start of a string, repeating it as often as needed, until the string is targetLength characters long. padEnd() does the same at the end. When padString is left out, a space is used. Both return a new string and leave the original alone.
Zero-padding numbers
Section titled “Zero-padding numbers”The padding methods belong to strings, so a number has to be converted first, with String() or toString(). Order numbers and clock times are typical uses.
const orderNumber = 482;const hours = 7;const minutes = 5;
console.log(String(orderNumber).padStart(6, '0'));console.log(`${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}`);console.log('Done'.padEnd(8, '!'));This prints:
00048207:05Done!!!!Lining up columns
Section titled “Lining up columns”padEnd() makes a left-aligned column and padStart() a right-aligned one, which suits numbers. This only lines up in a monospaced font, such as a terminal or a plain-text file.
const scores = [['Ana', 92], ['Bartholomew', 7], ['Cy', 100]];
for (const [name, score] of scores) { console.log(name.padEnd(12) + String(score).padStart(4));}This prints:
Ana 92Bartholomew 7Cy 100Fixed-width file formats, where each field takes an exact number of characters, are built the same way.
Hex colours
Section titled “Hex colours”A colour such as #ff0800 is three numbers from 0 to 255, each written as two hexadecimal digits. toString(16) gives a single digit for numbers below 16, so padStart(2, '0') is needed to keep each part two digits long.
const toHex = (n) => n.toString(16).padStart(2, '0');const rgbToHex = (r, g, b) => `#${toHex(r)}${toHex(g)}${toHex(b)}`;
console.log(rgbToHex(255, 8, 0));console.log(rgbToHex(0, 128, 64));This prints:
#ff0800#008040For a random colour, generate each part with Math.floor(Math.random() * 256). Multiplying by 255 instead is a common slip, because Math.random() never returns 1, so 255 could then never come up.
Edge cases
Section titled “Edge cases”A few behaviours are worth knowing:
- A
padStringthat does not fit a whole number of times is cut short. - A string already at or beyond
targetLengthcomes back unchanged, so padding never shortens a string. - An empty
padStringalso leaves the string unchanged. - A
padStringthat is not a string is converted to one, so the number0works as well as'0'. - Zero-padding a negative number puts the zeros before the minus sign.
console.log('abc'.padStart(8, '12345'));console.log('toolong'.padStart(3, '*'));console.log('x'.padStart(5, ''));console.log('7'.padStart(3, 0));console.log(String(-5).padStart(3, '0'));This prints:
12345abctoolongx0070-5To zero-pad a negative number, pad its absolute value and put the sign back.
const zeroPad = (n, width) => (n < 0 ? '-' : '') + String(Math.abs(n)).padStart(width, '0');
console.log(zeroPad(-5, 2));console.log(zeroPad(42, 4));This prints:
-050042targetLength counts UTF-16 code units, like length, so a filler made of emoji can be cut in half. charCodeAt vs codePointAt explains why.
Steve Griffith covers this topic in his video String Padding with padStart & padEnd.