ES.stage3: string padding

By Axel Rauschmayer

The following ECMAScript proposal is at stage 3: “String padding” by Jordan Harband & Rick Waldron. This blog post explains it.

For information on stages and ECMAScript 2016, consult the post “What’s in ECMAScript 2016 (ES7)?”.

Padding strings

The main use case for padding strings is displaying tabular data in a monospaced font. With padding, you can left-justify or right-justify the contents of a “cell”.

String.prototype.padStart(maxLength, fillString=' ')

This method (possibly repeatedly) prefixes the receiver with fillString, until its length is maxLength:

    > 'x'.padStart(5, 'ab')

If necessary, a fragment of fillString is used so that the result’s length is exactly maxLength:

    > 'x'.padStart(4, 'ab')

If the receiver is as long as, or longer than, maxLength, it is returned unchanged:

    > 'abcd'.padStart(2, '#')

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')

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
            .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')
    > 'x'.padEnd(4, 'ab')
    > 'abcd'.padEnd(2, '#')
    > 'abc'.padEnd(10, '0123456789')
    > '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?

There will be trimLeft and trimRight, but only for reasons of backward compatibility:

In this discussion it was noted that the words left and right don’t make sense for bidirectional and right-to-left languages. A more appropriately name for these functions would be trimStart and trimEnd which corresponds to the existing startsWith and endsWith.

Unfortunately, all engines already implement them and removing them would likely break the web.

Source:: 2ality