CyrefJS
CCyrefJS
فا
Back to documentation
String/Since 1.38.0

pad

Pads a string on both sides with repeating characters until it reaches the specified length.

pad(value, length, chars):string

Length validation

length must be an integer greater than or equal to zero. Otherwise, the function throws a RangeError with the message "pad: length must be a non-negative integer".

Unicode-aware length

Both the input value and padding characters are converted with Array.from. This means padding length calculations use Unicode code points.

Padding distribution

The required padding is split between the left and right sides. The left side receives floor(paddingLength / 2), while the right side receives the remaining characters. Therefore, an odd padding length gives the right side one extra character.

Repeating padding characters

When chars contains multiple characters, they are selected cyclically using their index modulo the number of padding characters.

When padding is unnecessary

If the value already has the target length or is longer, or if chars is empty, the original value is returned unchanged.

Parameters

valuestringrequired

The string to pad.

lengthnumberrequired

The target length of the resulting string. Must be a non-negative integer.

charsstringoptional

The characters used for padding. The characters are repeated cyclically.

Default:" "

Returns

string

The original string padded on both sides until it reaches the target length, or the original string when padding is unnecessary.

Errors

Throws a RangeError if length is not a non-negative integer.

Examples

01

Basic usage

Pad a string with spaces on both sides.

TypeScript
import { pad } from "@cyref/js";

pad("hello", 9);
// "  hello  "
02

Custom characters

Use a custom character for padding.

TypeScript
pad("hello", 9, "*");
// "**hello**"
03

Multiple padding characters

Padding characters are repeated cyclically when more than one character is provided.

TypeScript
pad("hello", 11, "ab");
// "abhelloabab"
04

Odd padding length

When the required padding is odd, the right side receives one more character than the left.

TypeScript
pad("hello", 10, "-");
// "--hello---"
05

No padding needed

If the string is already at least the target length, it is returned unchanged.

TypeScript
pad("hello", 3);
// "hello"
06

Empty padding characters

An empty chars string disables padding and returns the original value.

TypeScript
pad("hello", 10, "");
// "hello"
07

Unicode characters

The target length is measured using Array.from, which counts Unicode code points rather than UTF-16 code units.

TypeScript
pad("😀", 3, "-");
// "-😀-"
08

Invalid length

A negative or non-integer length throws a RangeError.

TypeScript
pad("hello", -1);
// RangeError: pad: length must be a non-negative integer
Built with@cyref/js·Official documentation