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!





Did you enjoy this post?

Cool if I slip into your inbox with more?
Full posts, 1-2 times per week: