0
0
JavascriptHow-ToBeginner · 3 min read

How to Pad String in JavaScript: Simple Guide

In JavaScript, you can pad strings using the padStart() and padEnd() methods. These methods add characters to the start or end of a string until it reaches a specified length.
📐

Syntax

The two main methods to pad strings are padStart(targetLength, padString) and padEnd(targetLength, padString).

  • targetLength: The desired length of the final string after padding.
  • padString (optional): The string to pad with. Defaults to a space if not provided.
javascript
str.padStart(targetLength, padString)
str.padEnd(targetLength, padString)
💻

Example

This example shows how to pad a string to a length of 10 by adding zeros at the start or spaces at the end.

javascript
const original = '123';
const paddedStart = original.padStart(10, '0');
const paddedEnd = original.padEnd(10, ' ');

console.log('Padded Start:', paddedStart);
console.log('Padded End:', `'${paddedEnd}'`);
Output
Padded Start: 0000000123 Padded End: '123 '
⚠️

Common Pitfalls

Common mistakes include:

  • Not providing padString, which defaults to space and may not be what you want.
  • Using a targetLength smaller than the original string length, which returns the original string unchanged.
  • Passing an empty string as padString, which causes no padding.
javascript
const str = 'abc';

// Wrong: empty padString does nothing
console.log(str.padStart(5, '')); // Output: 'abc'

// Right: provide a padString
console.log(str.padStart(5, '0')); // Output: '00abc'

// targetLength smaller than string length returns original
console.log(str.padEnd(2, '*')); // Output: 'abc'
Output
abc 00abc abc
📊

Quick Reference

MethodDescriptionDefault pad character
padStart(targetLength, padString)Pads the start of the string to target lengthSpace (' ')
padEnd(targetLength, padString)Pads the end of the string to target lengthSpace (' ')

Key Takeaways

Use padStart() to add characters at the beginning of a string.
Use padEnd() to add characters at the end of a string.
If padString is omitted, spaces are used by default.
If targetLength is less than the string length, the original string is returned.
Avoid empty padString as it results in no padding.