padString
Pads a string on both sides to reach the desired total length. If the target length is less than or equal to the original string length, the original string is returned unchanged.
1/**
2 * Pads a string on both sides to reach the desired total length.
3 * If the target length is less than or equal to the original string length,
4 * the original string is returned unchanged.
5 *
6 * @param str - The string to pad.
7 * @param length - The desired total length of the final string.
8 * @param padChar - The character to use for padding (default is a space).
9 * @returns The padded string.
10 */
11export function padString(str: string, length: number, padChar: string = ' '): string {
12 const totalPadding = Math.max(length - str.length, 0);
13 const left = Math.floor(totalPadding / 2);
14 const right = totalPadding - left;
15 return padChar.repeat(left) + str + padChar.repeat(right);
16}
Symmetric Padding
Ensures even distribution of padding on both sides, improving aesthetics for centered text in UI elements like buttons or tables.
Customizable Padding Character
Supports any padding character — spaces, dashes, underscores, etc., giving full control over output style.
Non-Destructive
If the desired length is less than or equal to the original string length, the input is returned untouched, preventing unexpected trimming.
Minimal and Efficient
Simple implementation with clear logic using basic string operations — lightweight and dependency-free.
Tests | Examples
1test('padString - pads evenly on both sides', () => {
2 expect(padString('abc', 7)).toBe(' abc ');
3});
4
5test('padString - pads with custom character', () => {
6 expect(padString('abc', 8, '-')).toBe('--abc---');
7});
8
9test('padString - string already meets or exceeds length', () => {
10 expect(padString('hello world', 5)).toBe('hello world');
11});
12
13test('padString - exact match to length', () => {
14 expect(padString('test', 4)).toBe('test');
15});
16
17test('padString - pads with odd total padding', () => {
18 expect(padString('abc', 6, '.')).toBe('.abc..');
19});
20
21test('padString - pads empty string', () => {
22 expect(padString('', 4, '*')).toBe('****');
23});
Common Use Cases
Centering Labels in Console Output or Logs
Visually align text within fixed-width terminal output or ASCII tables.
Formatting UI Elements (e.g., badges, tags, or buttons)
Ensure uniform appearance of strings inside UI components by equalizing length visually.
Text-Based Placeholder Rendering
When generating mock content or scaffolding UI without actual data, padded strings help simulate layout.
Improving Readability in Reports
Align data points or field names in CLI tools or markdown-based reports for better legibility.