Javascript - .padStart() and .padEnd()
Code Life
By Pierre Marsaa
Padding the Start of a String
Suppose you are printing a battle scoreboard and want every score to line up in a neat column. Because "7", "42", and "530" do not have the same number of digits, the output looks uneven:
↗️
Loading editor...
↶
↷
The .padStart(targetLength, padString) method solves this by adding characters to the beginning of a string until it reaches the desired length:
1.
targetLength is the total character length you want the final string to have.
2.
padString is the character used to fill the missing space.
↗️
Loading editor...
↶
↷
Here, "7" becomes "007" and "42" becomes "042", while "530" already has 3 characters so nothing is added. Now every line has the exact same width!
Verify