Use padStart() or padEnd() to add padding
const num = '5';
const padded = num.padStart(3, '0');
console.log(padded); // "005"// Format numbers with leading zeros
const ids = [1, 42, 123];
const formatted = ids.map(id =>
String(id).padStart(4, '0')
);
console.log(formatted);
// Align text
const items = ['Apple', 'Banana', 'Kiwi'];
items.forEach(item => {
const aligned = item.padEnd(10, '.');
console.log(`${aligned} $5.99`);
});
// Format time
const hours = 9, minutes = 5;
const time = `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}`;
console.log(time);function center(str, width) {
const padLen = Math.floor((width - str.length) / 2);
return str.padStart(str.length + padLen).padEnd(width);
}const aligned = text.padStart(20, ' ');Avoid manual string concatenation
// DON'T DO THIS
var padded = '';
while (padded.length + str.length < width) {
padded += '0';
}
padded += str;✓ Works in all modern browsers (ES2017+)