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 319 views
2 answers 266 views
1 answer 220 views
1 answer 195 views
1 answer 189 views
1 answer 197 views
1 answer 212 views
...