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 132 views
2 answers 129 views
1 answer 104 views
1 answer 90 views
1 answer 84 views
1 answer 83 views
1 answer 93 views
...