Padding strings and numbers with JavaScript

Josh Sherman
1 min read
Software Development 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!

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

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.

Currently Reading

Parasie Eve

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles