Pad String on Both Sides
Pads a string on both sides with a specified character until it reaches the desired length.
- string
- pad
- manipulation
Install
npx shadcn@latest add https://quicksnip.dev/r/pad-string-on-both-sides.jsonThis snippet is not verified yet. Review it before use, or help verify it.
Code
function padString(str, length, char = ' ') {
const totalPad = length - str.length;
const padStart = Math.floor(totalPad / 2);
const padEnd = totalPad - padStart;
return char.repeat(padStart) + str + char.repeat(padEnd);
}Usage
padString('hello', 10, '*'); // Returns: '**hello***'