String Utilities
repeatPad
Pads a string evenly on both sides until it reaches the desired length
Usage
import { repeatPad } from '@/lib/repeat-pad';
const result = repeatPad("TS", 6, "-");
console.log(result); // "--TS--"Installation
pnpm dlx shadcn@latest add https://utilcn.dev/r/repeat-pad.jsonbunx --bun shadcn@latest add https://utilcn.dev/r/repeat-pad.jsonnpx shadcn@latest add https://utilcn.dev/r/repeat-pad.jsonyarn shadcn@latest add https://utilcn.dev/r/repeat-pad.jsonParameters
| Parameter | Type | Default | Description |
|---|---|---|---|
str | string | - | The input string |
length | number | - | Desired total length |
pad | string | ' ' | The character/string used as padding |
Returns
string - The padded string centered with the given padding.
Examples
repeatPad("TS", 6, "-"); // "--TS--"
repeatPad("Hello", 11, " "); // " Hello "
repeatPad("JS", 5, "*"); // "*JS**" (odd padding goes to the right)
repeatPad("Test", 10, "="); // "===Test==="
repeatPad("A", 7, "0"); // "000A000"Implementation
export function repeatPad(str: string, length: number, pad = ' '): string {
const total = Math.max(length - str.length, 0);
const left = Math.floor(total / 2);
const right = total - left;
return pad.repeat(left) + str + pad.repeat(right);
}