padEnd String Method in JavaScript
With padEnd
, it adds characters to the end of a string so it reaches a specified length. This is great for us to add some padding to display our strings in a tabular format. Isn’t it so much easier to read, yay 🍹
// Display String in Tabular Format with padEnd// ❌
'Day: Monday' + 'Drink: 🍵'
'Day: Saturday' + 'Drink: 🍹'// ✅
'Day: Monday'.padEnd(20) + 'Drink: 🍵'
'Day: Saturday'.padEnd(20) + 'Drink: 🍹'
padEnd Parameters
The padEnd
accepts 2 parameters:
string.padEnd( <length>, <character>)
1st Parameter: Length
This is the final length of your result string. It is required.
Let’s say you begin with a string that has 3 characters. And you set the length to be 5 characters. That means, padEnd
will pad it with 2 characters so the total length meets your target length of 5 characters.
Here’s an example. I’m denoting the space character with ·
to show you the padded space.
'abc'.padEnd(5);// abc··
2nd Parameter: Character
This is an optional parameter. As you see from above, the default padded character is an empty…