Emmanuel Akinfulubi

JavaScriptString

Pad a string to a fixed length in JavaScript

Beginner · 3 min read

Padding means adding characters to a string until it reaches a certain width. You use it to turn 7 into 007 for a ticket number, to line up a column of prices in a receipt, or to fill a label with dots up to a fixed width, like the lines in a table of contents.

JavaScript has two methods for it: padStart adds characters on the left, and padEnd adds them on the right. In this tutorial you will pad '7' to three characters with zeros and 'ab' to five with dots, then see what happens when you ask for a width shorter than the string. You only need to know what a string is and how to read its length.

The number is the final width

The most important thing to know about padding: the number you pass is the total length you want, not how many characters to add.

Width

'7'.padStart(3, '0')   ->  '007'    3 characters in total, so 2 zeros are added

Read it as "make this string 3 wide, filling the left with '0'". The second argument, the filler, is the text to fill with. If you leave it out, the filler is a space.

Here is the exercise. Have a go yourself first, or read on and we will build it together.

19 Pad a string to a width

easy

Pad '7' out to three characters with zeros, and 'ab' out to five with dots. Then ask for a width shorter than the string.

Stuck? Three hints, smallest first
  1. 1. The argument is the total length wanted, not the number of characters to add.
  2. 2. padStart adds on the left, padEnd on the right.
  3. 3. Neither ever truncates, and a multi-character filler is cut to fit.

Step 1: pad on the left

Step 1

console.log('7'.padStart(3, '0'));        // '007'
console.log('7'.padStart(3, '0').length); // 3

The result is exactly 3 characters long. '7' was 1 character, so two zeros were added in front.

Step 2: pad on the right

Step 2

console.log('ab'.padEnd(5, '.')); // 'ab...'

Same idea, other side. 'ab' is 2 characters, so three dots are added after it to reach 5.

Step 3: the default filler is a space

Step 3

console.log(JSON.stringify('ab'.padStart(4))); // "  ab"

With no filler, two spaces are added. This is how you right-align text in a fixed-width column: every value is padded on the left to the same width. JSON.stringify adds quotes when printing so you can see the spaces.

Step 4: ask for a width that is too small

What happens when the string is already longer than the width you ask for?

Step 4

console.log('lagos'.padStart(2, '0'));        // 'lagos'
console.log('lagos'.padStart(2, '0').length); // 5
console.log('abc'.padStart(3, '0'));          // 'abc'

Nothing happens. Padding only ever adds characters; it never cuts any off. 'lagos' is already 5 wide, more than 2, so it comes back as it was. Asking for exactly the current length is also a no-op.

This is the thing to plan around. If a column must be exactly 6 characters, padding alone won't stop a 9-character value from spilling over. You need slice as well, for example text.slice(0, 6).padEnd(6).

Step 5: a filler longer than one character

The filler can be more than one character. It is repeated as many times as needed, and the last copy is cut to fit.

Step 5

console.log('x'.padEnd(6, 'ab'));      // 'xababa'
console.log('x'.padStart(5, ''));      // 'x'

'x' needs 5 more characters. Two full copies of 'ab' make 4, and the third copy is cut to just 'a'. An empty filler has nothing to repeat, so nothing is added at all.

Step 6: the original stays the same

Step 6

const s = '7';
const padded = s.padStart(3, '0');
console.log(padded); // '007'
console.log(s);      // '7'

Like every string method, padding gives you a new string. Strings in JavaScript can't be changed once they are made, so s is still '7'.

The full solution

Here is the complete answer: both directions, the default space, a long filler, and a width that is too small. Press Run to see the output.

The answer

console.log("'7'.padStart(3, '0')  :", '7'.padStart(3, '0'));
console.log("'ab'.padEnd(5, '.')   :", 'ab'.padEnd(5, '.'));
console.log("'x'.padEnd(6, 'ab')   :", 'x'.padEnd(6, 'ab'), '<- the filler repeats and is cut');
console.log("'lagos'.padStart(2)   :", 'lagos'.padStart(2), '<- shorter target, so nothing happens');

Output


      
10 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 10 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

10 checks

test('padStart pads on the left to a total length', '7'.padStart(3, '0'), '007');
test('padEnd pads on the right', 'ab'.padEnd(5, '.'), 'ab...');
test('the default filler is a space', 'ab'.padStart(4), '  ab');
test('the argument is the total length, not the amount added', '7'.padStart(3, '0').length, 3);
test('a target shorter than the string does nothing', 'lagos'.padStart(2, '0'), 'lagos');
test('so padding never truncates', 'lagos'.padStart(2, '0').length, 5);
test('a multi-character filler repeats and is cut to fit', 'x'.padEnd(6, 'ab'), 'xababa');
test('an empty filler pads nothing at all', 'x'.padStart(5, ''), 'x');
test('padding to the same length is a no-op', 'abc'.padStart(3, '0'), 'abc');
test('and the original is never modified', (() => { const s = '7'; s.padStart(3, '0'); return s; })(), '7');

Read the argument as "make it this wide", not "add this many". '7'.padStart(3, '0') is '007', not '0007'.

The non-truncating behaviour is the thing to design around. If a column has a hard width, padding alone will not enforce it — you need slice as well, which exercises 21 and 63 both do.

Common mistakes

  • Passing the number of characters to add. '7'.padStart(2, '0') is '07', not '007'. The number is the final width.
  • Expecting padding to shorten long text. It never truncates. Use slice to cut first.
  • Calling padStart on a number. (7).padStart(3, '0') throws a TypeError, because numbers don't have string methods. Convert first with String(7).

Try it yourself

  1. Print 'Rice' and 'Beans' padded to 10 characters with dots, followed by a price, so the prices line up.
  2. Write fixedWidth(text, width) that pads short text with spaces and cuts long text, so the result is always exactly width long.
  3. Use padStart with the filler '*' to show only the last four digits of '1234' as '********1234'.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.