How to pad a string in JavaScript
ES2017 added the padStart()
and padEnd()
methods, which add whitespace or other characters to a string until it reaches a specific length.
What is padding a string?
Padding a string in JavaScript refers to filling a string up with a repeated character or string of characters, usually whitespace.
The string is padded to a certain length, which is what is passed to the String.prototype methods .padStart()
and .padEnd()
.
Calling .padStart(length)
or .padEnd(length)
returns a new string of the given length, with the start or end of the string padded with spaces.
These padding functions do not modify the string that they are called on.
Both .padStart()
and .padEnd()
take two parameters, the length in characters to pad the string to and the string to be repeated while padding: