The ECMAScript proposal “String padding” by Jordan Harband & Rick Waldron is part of ECMAScript 2017. This blog post explains it.
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:
> 'x'.padStart(5, 'ab')
'ababx'
If necessary, a fragment of fillString is used so that the result’s length is exactly maxLength:
> 'x'.padStart(4, 'ab')
'abax'
If the receiver is as long as, or longer than, maxLength, it is returned unchanged:
> 'abcd'.padStart(2, '#')
'abcd'
If maxLength and fillString.length are the same, fillString becomes a mask into which the receiver is inserted, at the end:
> 'abc'.padStart(10, '0123456789')
'0123456abc'
If you omit fillString, a string with a single space in it is used (' '):
> 'x'.padStart(3)
' x'
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.padStart =
function (maxLength, fillString=' ') {
let str = String(this);
if (str.length >= maxLength) {
return str;
}
fillString = String(fillString);
if (fillString.length === 0) {
fillString = ' ';
}
let fillLen = maxLength - str.length;
let timesToRepeat = Math.ceil(fillLen / fillString.length);
let truncatedStringFiller = fillString
.repeat(timesToRepeat)
.slice(0, fillLen);
return truncatedStringFiller + str;
};
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:
> 'x'.padEnd(5, 'ab')
'xabab'
> 'x'.padEnd(4, 'ab')
'xaba'
> 'abcd'.padEnd(2, '#')
'abcd'
> 'abc'.padEnd(10, '0123456789')
'abc0123456'
> 'x'.padEnd(3)
'x '
Only the last line of an implementation of padEnd() is different, compared to the implementation of padStart():
return str + truncatedStringFiller;
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.