How to pad a string on both sides in Node.js

1 Answer

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

console.log(padBoth("Node", 9, '*'));



/*
run:

**Node***

*/
 

 



answered Jul 6, 2025 by avibootz

Related questions

3 answers 140 views
2 answers 139 views
1 answer 108 views
1 answer 97 views
1 answer 95 views
1 answer 89 views
1 answer 106 views
...