Back to Home
Strings

How to Pad Strings

Use padStart() or padEnd() to add padding

Quick Answer (2024 ES6+ Way)

javascript
const num = '5';
const padded = num.padStart(3, '0');
console.log(padded); // "005"

Live Example

javascript
// 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);

Common Variations

Center Text
javascript
function center(str, width) {
  const padLen = Math.floor((width - str.length) / 2);
  return str.padStart(str.length + padLen).padEnd(width);
}
Right Align
javascript
const aligned = text.padStart(20, ' ');

❌ Don't Do This (Outdated Way)

Avoid manual string concatenation

javascript
// DON'T DO THIS
var padded = '';
while (padded.length + str.length < width) {
  padded += '0';
}
padded += str;

Browser Support

Works in all modern browsers (ES2017+)

#strings#pad#format