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