1.38.0pad
Pads a string on both sides with repeating characters until it reaches the specified length.
pad(value, length, chars):stringLength 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
valuestringrequiredThe string to pad.
lengthnumberrequiredThe target length of the resulting string. Must be a non-negative integer.
charsstringoptionalThe characters used for padding. The characters are repeated cyclically.
" "Returns
stringThe 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
Basic usage
Pad a string with spaces on both sides.
import { pad } from "@cyref/js";
pad("hello", 9);
// " hello "Custom characters
Use a custom character for padding.
pad("hello", 9, "*");
// "**hello**"Multiple padding characters
Padding characters are repeated cyclically when more than one character is provided.
pad("hello", 11, "ab");
// "abhelloabab"Odd padding length
When the required padding is odd, the right side receives one more character than the left.
pad("hello", 10, "-");
// "--hello---"No padding needed
If the string is already at least the target length, it is returned unchanged.
pad("hello", 3);
// "hello"Empty padding characters
An empty chars string disables padding and returns the original value.
pad("hello", 10, "");
// "hello"Unicode characters
The target length is measured using Array.from, which counts Unicode code points rather than UTF-16 code units.
pad("😀", 3, "-");
// "-😀-"
Invalid length
A negative or non-integer length throws a RangeError.
pad("hello", -1);
// RangeError: pad: length must be a non-negative integer