Aller au contenu principal

pad()

pad(str, length, chars): string

Pads string on the left and right sides if it's shorter than length.

DEPRECATED

Use padStart and padEnd combination directly instead.


Parameters

str: string | null | undefined

The string to pad.

length: number | null | undefined

The target length.

chars: string = " "

The string used as padding.


Returns: string

The padded string.


See Also


Since

2.0.0


Also known as

pad (Lodash, es-toolkit) · ❌ (Remeda, Radashi, Ramda, Effect, Modern Dash, Antfu)


Example

// ❌ Deprecated approach
pad('abc', 8); // => ' abc '
pad('abc', 8, '_-'); // => '_-abc_-_'
pad('abc', 3); // => 'abc'

// ✅ Recommended approach
const str = 'abc';
const length = 8;
const padLength = Math.max(0, length - str.length);
const leftPad = Math.floor(padLength / 2);
const rightPad = padLength - leftPad;
str.padStart(str.length + leftPad).padEnd(length);
// => ' abc '

How it works?

Pads string on both sides to target length. Deprecated: Use padStart() and padEnd() combination.

Native Equivalent

// ❌ pad(str, length, chars)
// ✅ str.padStart((str.length + length) / 2, chars).padEnd(length, chars)

Use Cases

Pad to fixed width 📌

Pad string to fixed length.

"5".padStart(3, "0");   // => "005"
"5".padEnd(3, "0"); // => "500"

Format numbers

Add leading zeros.

const id = String(num).padStart(5, "0");
// 42 => "00042"

Align text

Create aligned columns.

const label = name.padEnd(20);
const value = price.padStart(10);