utilcn logoutilcn
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.json
bunx --bun shadcn@latest add https://utilcn.dev/r/repeat-pad.json
npx shadcn@latest add https://utilcn.dev/r/repeat-pad.json
yarn shadcn@latest add https://utilcn.dev/r/repeat-pad.json

Parameters

ParameterTypeDefaultDescription
strstring-The input string
lengthnumber-Desired total length
padstring' '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);
}