Padding Strings with padStart and padEnd
You'll learn how to expand strings to a specific length by adding characters to the beginning or end.
What is String Padding?
Sometimes you need a string to be a certain length, and you want to fill in the extra space with specific characters. String padding adds characters (by default, spaces) to either the start or end of a string until it reaches your desired length.
Think of it like formatting numbers on a receipt—you might want all prices to line up nicely by adding spaces or zeros to make each number the same width.
Using padStart()
The padStart() method adds characters to the beginning of a string:
let code = '5';
let paddedCode = code.padStart(3, '0');
// paddedCode is '005'
let name = 'Ana';
let paddedName = name.padStart(10, ' ');
// paddedName is ' Ana' (7 spaces added)
Using padEnd()
The padEnd() method adds characters to the end of a string:
let item = 'Apple';
let paddedItem = item.padEnd(10, '.');
// paddedItem is 'Apple.....' (5 dots added)
let price = '12';
let paddedPrice = price.padEnd(5, '0');
// paddedPrice is '12000'
How It Works
Both methods take two parameters:
- Target length: the final length you want
- Pad string (optional): the character(s) to fill with (defaults to a space)
If the original string is already equal to or longer than the target length, it returns the string unchanged.
let long = 'Hello World';
long.padStart(5, 'x');
// Still 'Hello World' (already longer than 5)
Key Takeaway: Use padStart() and padEnd() to extend strings to a target length by adding fill characters to the beginning or end, perfect for formatting and alignment.