Skip to content

pad

Import from @varavel/vdl-plugin-sdk/utils/strings.

function pad(
   str, 
   length, 
   chars?): string;

Pads both sides of a string until it reaches the requested length.

Padding is only added when the string is shorter than length. The padding pattern repeats as needed and is truncated to fit exactly. When the total number of padding characters cannot be split evenly, the right side receives one more character than the left side.

By default, spaces are used as padding. Pass chars to use a custom padding pattern. If chars is an empty string, the input is returned unchanged.

The target length is truncated with Math.trunc, so decimal lengths behave predictably. Non-finite lengths are ignored and return the original string.

Parameters

Parameter Type Description
str string String to pad.
length number Final string length to target.
chars? string Optional padding characters to repeat.

Returns

string

str centered within the requested width.

Examples

pad("cat", 7)
// "  cat  "
pad("cat", 8, "_-")
// "_-cat_-_"