padStart
and padEnd
This chapter explains the ECMAScript 2017 feature “String padding” by Jordan Harband & Rick Waldron.
ECMAScript 2017 has two new string methods:
Use cases for padding strings include:
'file 001.txt'
'Test 001: ✓'
'0x00FF'
String.prototype.padStart(maxLength, fillString=' ')
This method (possibly repeatedly) prefixes the receiver with fillString
, until its length is maxLength
:
If necessary, a fragment of fillString
is used so that the result’s length is exactly maxLength
:
If the receiver is as long as, or longer than, maxLength
, it is returned unchanged:
If maxLength
and fillString.length
are the same, fillString
becomes a mask into which the receiver is inserted, at the end:
If you omit fillString
, a string with a single space in it is used (' '
):
padStart()
The following implementation gives you a rough idea of how padStart()
works, but isn’t completely spec-compliant (for a few edge cases).
String.prototype.padEnd(maxLength, fillString=' ')
padEnd()
works similarly to padStart()
, but instead of inserting the repeated fillString
at the start, it inserts it at the end:
Only the last line of an implementation of padEnd()
is different, compared to the implementation of padStart()
:
padStart
and padEnd
padLeft
and padRight
? For bidirectional or right-to-left languages, the terms left
and right
don’t work well. Therefore, the naming of padStart
and padEnd
follows the existing names startsWith
and endsWith
.