Goal: To understand and learn how padding a string in JavaScript works.
String.prototype.padEnd()
padEnd()
is a string method which pads the end of the current string with a strPadding up to a specified length.
Syntax
padEnd(specifiedLength)
padEnd(specifiedLength, strPadding)
The specifiedLength
is the length of the resulting string once the padding has been applied to the current string. Note that if this value is less than the current string's length there will be no visible change.
The strPadding
is the specific string that will be applied to pad the end of the current string. This parameter is optional. Note that if the length of this string padding is greater than the specifiedLength
, it will be cut or shortened to fit within the specifiedLength
.
Examples
let sayIt = 'Please'
console.log(sayIt.padEnd(12)) //"Please "
console.log(sayIt.padEnd(12,'*')) //"Please******"
console.log(sayIt.padEnd(8,'***')) //"Please**"
console.log(sayIt.padEnd(5)) //"Please"
Since there was no specified strPadding
on the first example, spaces are applied instead.
String.prototype.padStart()
padStart()
is another string method which pads the current string and works similarly with padEnd()
but on this method the padding is applied at the beginning of the current string. A strPadding
will be applied to pad the start of the current string to meet the specifiedLength
.
Syntax
padStart(specifiedLength)
padStart(specifiedLength, strPadding)
Examples
let callMe = 'Maybe'
console.log(callMe.padStart(10)) //" Maybe"
console.log(callMe.padStart(6,'*')) //"*Maybe"
console.log(callMe.padStart(7,'123')) //"12Maybe"
console.log(callMe.padStart(1)) //"Maybe"
On example 3, the length of our current string is 5 and we wanted to pad the start with '123'
. Since the length of the resulting string is 7, only '12'
was applied at the start and the last one which is '3'
was cut off.
Again it is important to note the relationship between specifiedLength
and strPadding
and with the current string. If the specifiedLength
is less than the length of the current string then there will be no change to the resulting string and if the length of strPadding
is way too long than the specifiedLength
then it will be cut or shortened to fit in the criteria of the specifiedLength
.
This concludes the tutorial about the padEnd()
and padStart()
methods of a string in JavaScript. I hope you enjoyed reading and that it helped you understand how these methods work.
Top comments (0)