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 146 views
2 answers 145 views
1 answer 119 views
1 answer 102 views
1 answer 105 views
1 answer 95 views
1 answer 115 views
...