padStart & padEnd: How to Pad a String with Characters

Sometimes you need to add a certain number of characters to a string to make it a specific length. This is where padStart and padEnd come in handy.

padStart

padStart adds characters to the beginning of a string until it reaches a specified length. It takes two arguments: the total length of the string and the string to pad it with. If the string is already longer than the specified length, it will be returned as-is.

Loading Code . . .

In the example above, we pad the string '5' with the character '0' until it reaches a length of 3. The result is '005'. It can be useful to pad numbers with leading zeros, what is very common in some situations like video games scores.

padEnd

padEnd adds characters to the end of a string until it reaches a specified length. It takes two arguments: the total length of the string and the string to pad it with. If the string is already longer than the specified length, it will be returned as-is.

Loading Code . . .

In the example above, we pad the string 'Hello' with the character '!' until it reaches a length of 10. The result is 'Hello!!!!!'.

Tips

Remember that padStart and padEnd are string methods, so you need to call them on a string. If you want to pad a number, you need to convert it to a string first.

Loading Code . . .

Code Challenge

Create a function called center that takes a string called word and a number called width. The function should return the string word centered in a string of * characters of length width.

Ex: center('abcd', 10) should return '***abcd***'.

The word size and the width will always be even numbers.

Loading...
Loading...
Loading...

© 2024 - ®Mewters