Pad a string with padStart and padEnd in JavaScript
Beginner · 3 min read
Ticket numbers like 000087, clock times like 09:05, and receipts where the prices line up in a neat column all have one thing in common: text padded out to a fixed width. JavaScript has two methods built for this, padStart and padEnd.
In this tutorial you will turn the ticket number 87 into 000087 and pad a menu label with dots, then test the edges: text that is already too long, a pad of more than one character, and what happens when you call the method on a number. You need to know what a string is and how to call a method.
What padding means
Padding adds characters to one side of a string until it reaches a length you choose.
padStart(width, pad)adds them on the left, at the start.padEnd(width, pad)adds them on the right, at the end.
The first argument is the most important idea in this lesson: it is the total width you want at the end, not how many characters to add.
console.log('7'.padStart(3, '0')); // 007
console.log('42'.padStart(3, '0')); // 042
Both results are three characters long. '7' needed two zeros to get there, '42' needed one. You say how wide, and JavaScript works out how much to add.
Here is the exercise. Try it yourself first if you like, or read on and we will build it together.
103 padStart and padEnd for a fixed width
easyPrint a ticket number as six digits with leading zeros, and a menu label padded out to a ten-character column with dots. Then check what happens when the text is already longer than the width, and when the pad is more than one character.
Stuck? Three hints, smallest first
- 1. Both take the total width you want, not how many characters to add.
- 2. Neither ever shortens anything.
- 3. They are string methods, so a number needs
String(n)first.
Step 1: leading zeros on a ticket number
const ticket = 87;
const padded = String(ticket).padStart(6, '0');
console.log(padded); // 000087
console.log(padded.length); // 6
ticket is a number, and these are string methods, so String(ticket) turns it into the text '87' first. Then padStart(6, '0') adds four zeros on the left to make six characters.
Step 2: dots after a menu label
const label = 'Suya'.padEnd(10, '.');
console.log(label + '|'); // Suya......|
'Suya' has four letters, so padEnd(10, '.') adds six dots on the right. The | is only there so you can see where the string ends. If every label in a menu is padded to 10, the prices that follow them start in the same column.
Step 3: text that is already too long
What if the text is wider than the width you ask for?
const tooLong = 'LAGOS-IBADAN'.padStart(5, '0');
console.log(tooLong); // LAGOS-IBADAN
console.log(tooLong.length); // 12
Nothing happens. The string comes back exactly as it was. Padding only ever makes text longer; it never cuts it down. If a column must never be wider than 10 characters, you need to cut the text yourself with slice as well.
Step 4: a pad longer than one character
The pad can be more than one character. JavaScript repeats it, then cuts it to fit:
console.log('7'.padStart(6, 'ab')); // ababa7
Six characters are needed, '7' is one, so five pad characters go on the left: a, b, a, b, a. The pattern is cut off in the middle; you don't always get whole copies of it.
If you leave the pad out, it is a space:
console.log('A'.padStart(3) === ' A'); // true
Step 5: the mistake everyone makes once
Calling padStart straight on a number fails:
const ticket = 87;
try {
ticket.padStart(6, '0');
} catch (err) {
console.log(err.name); // TypeError
}
Numbers don't have a padStart method, so JavaScript throws a TypeError, the error it uses when you try to call something that isn't a function. try and catch let the code carry on so you can see the error's name. The fix is the String(ticket) from Step 1.
The full solution
The answer panel pads the ticket and the menu label, then tries the edge cases: too long, a two-character pad, and the number that has no padStart. Press Run to see the output and the checks.
const ticket = 87;
const padded = String(ticket).padStart(6, '0');
const label = 'Suya'.padEnd(10, '.');
// Neither one truncates. A string already past the width comes back untouched.
const tooLong = 'LAGOS-IBADAN'.padStart(5, '0');
// A multi-character pad is repeated, then cut to fit the width exactly.
const fancy = '7'.padStart(6, 'ab');
// A number has no padStart, which is the mistake everyone makes once.
let numberThrew = '';
try {
ticket.padStart(6, '0');
} catch (err) {
numberThrew = err.name;
}
console.log(label + '|');
console.log('ticket:', padded, ' multi-character pad:', fancy);
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('leading zeros to a fixed width', padded, '000087');
test('the argument is the total width, not the padding added', padded.length, 6);
test('padEnd fills to the right', label, 'Suya......');
test('a string past the width is returned unchanged', tooLong, 'LAGOS-IBADAN');
test('so padding is not a way to truncate', tooLong.length, 12);
test('a multi-character pad is cut to fit', fancy, 'ababa7');
test('the default pad is a space', 'A'.padStart(3), ' A');
test('an empty string pads to full width', ''.padStart(3, '0'), '000');
test('a number has no such method', numberThrew, 'TypeError');
Also exercise 1, where padStart put a leading zero on a clock's minutes; here the angle is the width rule itself. The argument is the finished length, so padStart(6, '0') on three digits adds three zeros and on eight digits adds none — and adds none silently. If your columns must not exceed a width, pad and then slice, because padding alone will never shorten anything (exercise 37 does the cutting half).
Two smaller edges. A pad longer than one character is repeated and then chopped mid-pattern, so 'ab' gives ababa rather than a whole number of copies. And these live on String.prototype: 87 .padStart is undefined, so calling it is a TypeError. Wrap the number in String(...) before you pad it.
Common mistakes
- Passing how many characters to add.
'87'.padStart(4, '0')is'0087', not'000087'. The number is the final width. - Expecting padding to cut long text. It never shortens anything. Pad, then
slice, if you need an exact width. - Calling it on a number. When
ticketholds a number,ticket.padStartdoesn't exist. Wrap the number inString(...)first.
Try it yourself
- Write
clock(hours, minutes)that returns'09:05'forclock(9, 5). - Print three menu lines,
Suya,Jollof riceandPuff-puff, each padded with dots to 15 characters and followed by a price. - Write
fixedWidth(text, width)that pads short text with spaces and cuts long text, so the result is always exactlywidthcharacters.