How to pad a string on both sides in TypeScript

1 Answer

0 votes
function padBoth(str: string, totalLength: number, padChar: string = ' '): string {
    const half: number = Math.floor((totalLength - str.length) / 2);
    
    return str
        .padStart(str.length + half, padChar)
        .padEnd(totalLength, padChar);
}

console.log(padBoth("TS", 7, '*'));



/*
run:

"**TS***"

*/

 



answered Jul 6, 2025 by avibootz

Related questions

3 answers 151 views
2 answers 137 views
1 answer 108 views
1 answer 97 views
1 answer 95 views
1 answer 89 views
1 answer 106 views
...