ES proposal: string padding


The ECMAScript proposal “String padding” by Jordan Harband & Rick Waldron is part of ECMAScript 2017. This blog post explains it.



Padding strings

Use cases for padding strings include:



  • Displaying tabular data in a monospaced font.

  • Adding a count or an ID to a file name or a URL: 'file 001.txt'

  • Aligning console output: 'Test 001: ✓'

  • Printing hexadecimal or binary numbers that have a fixed number of digits: '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'

A simple implementation of 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;

FAQ: string padding

Why aren’t the padding methods called 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.



Comments

Popular posts from this blog

Steve Lopez and the Importance of Newspapers

Ideas for fixing unconnected computing

Omar to kill me