How to pad the start and end of strings in Javascript
March 31, 2020
Introduced in ES2017, the .padStart()
and .padEnd()
methods add padding to the front and back of a string in Javascript. Fundamentally, padding a string is simply adding characters to the start or end. For example, padding the string hello world
with 4 blank spaces at the start would look like this hello world
. Padding the end the string Goodbye
with 3 exclamation points would look like this Goodbye!!!
.
Using padStart() and padEnd()
Both .padStart()
and .padEnd()
do not modify the original string but return a new string with the added padding. Both methods take two parameters: the total number of characters for the new string and the character to use for padding.
The total number of characters for the new string includes the characters for the current string, so if you have a string that is 10
characters long and you want to add three padding characters to it you need to pass 13
into the first parameter.
For example, trailing dots
is 13 characters, to add 5 .
characters to the end of that string you need to pass in 18
into the first parameter.
1.const newStr = "trailing dots".padEnd(18, ".");2.3.// 'trailing dots..........'
If you pass in the number of padding characters that you want, 5
, it will not add anything to the string:
1.const newStr = "trailing dots".padEnd(5, ".");2.3.// 'trailing dots'
Default pad character
An empty space character, ' '
, is the default second parameter for both .padStart()
and .padEnd()
, which means you can pad a string with spaces with just one parameter.
1.const newStr = "padMe".padStart(10);2.3.// ' padMe'
Pad the start of a string in Javascript
To pad the beginning of the string use padStart()
:
1.const newStr = "string".padStart(10, "char");2.3.// 'charstring'
Pad the end of a string in Javascript
To pad the end of a string use padEnd()
:
1.const newStr = "string".padEnd(10, "char");2.3.// 'stringchar'