Padding strings and numbers with JavaScript

Programming languages can change pretty regularly, and I try to carve out some
time periodically to catch up on the latest and greatest the languages I love
have to offer.

With that, recently I was poking around on JavaScript’s string prototype and
came to realize that there were some string padding methods that I had no idea
existed.

What really blew my mind is that after I thought about it, I realized I can’t
remember the last time I needed to worry about padding a string in JavaScript.
It’s something that I’ve done quite regularly in PHP by way of str_pad() but
for whatever reason, haven’t had the same need with doing Node.js development.

Unlike PHP, JavaScript has two methods to handle padding, depending on which
side of a string you want to add the characters to. To pad a string with spaces,
you can do the following:

const str = 'Test'

// Prepend characters
console.log(str.padStart(10, ' '

// Append characters
console.log(str.padEnd(10, ' '

Both methods accept the number of characters you want to pad up to as well as
the character (or characters) you’d like to use to do the padding.

This is great for strings, but if you wanted to zero pad a number, you will need
to do a bit more work, to convert the number to a string:

const num = 123

// Prepend zeros
console.log(number.toString().padStart(6, 0

And you’re off to the races!

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.