Please support this book: buy it (PDF, EPUB, MOBI) or donate

8. New string methods: padStart and padEnd

This chapter explains the ECMAScript 2017 feature “String padding” by Jordan Harband & Rick Waldron.

8.1 Overview

ECMAScript 2017 has two new string methods:

  1. > 'x'.padStart(5, 'ab')
  2. 'ababx'
  3. > 'x'.padEnd(5, 'ab')
  4. 'xabab'

8.2 Why pad 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'

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

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

  1. > 'x'.padStart(5, 'ab')
  2. 'ababx'

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

  1. > 'x'.padStart(4, 'ab')
  2. 'abax'

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

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

If maxLength and fillString.length are the same, fillString becomes a mask into which the receiver is inserted, at the end:

  1. > 'abc'.padStart(10, '0123456789')
  2. '0123456abc'

If you omit fillString, a string with a single space in it is used (' '):

  1. > 'x'.padStart(3)
  2. ' x'

8.3.1 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).

  1. String.prototype.padStart =
  2. function (maxLength, fillString=' ') {
  3. let str = String(this);
  4. if (str.length >= maxLength) {
  5. return str;
  6. }
  7.  
  8. fillString = String(fillString);
  9. if (fillString.length === 0) {
  10. fillString = ' ';
  11. }
  12.  
  13. let fillLen = maxLength - str.length;
  14. let timesToRepeat = Math.ceil(fillLen / fillString.length);
  15. let truncatedStringFiller = fillString
  16. .repeat(timesToRepeat)
  17. .slice(0, fillLen);
  18. return truncatedStringFiller + str;
  19. };

8.4 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:

  1. > 'x'.padEnd(5, 'ab')
  2. 'xabab'
  3. > 'x'.padEnd(4, 'ab')
  4. 'xaba'
  5. > 'abcd'.padEnd(2, '#')
  6. 'abcd'
  7. > 'abc'.padEnd(10, '0123456789')
  8. 'abc0123456'
  9. > 'x'.padEnd(3)
  10. 'x '

Only the last line of an implementation of padEnd() is different, compared to the implementation of padStart():

  1. return str + truncatedStringFiller;

8.5 FAQ: padStart and padEnd

8.5.1 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.