Building text: repeat, pad and split

Text usually arrives in pieces: a label and a value, a row of columns, a list that has to become one line. JavaScript builds it with the plus sign, with repeat and the two padding methods, and with split and join where an array is the better shape in the middle. Every one of them returns a new string.

This lesson keeps to the methods themselves; the template literal that replaces most concatenation is the lesson after the next, and it builds on the same operations. The examples here are the ones a report uses: a header line, a column of numbers with leading zeros, a value typed with spaces around it and a comma separated row.

Concatenation with plus and +=

The plus sign joins two strings and converts the other operand when only one side is text. += appends to a name, which is the loop that builds a line piece by piece. The conversion is the trap of the previous lesson: a number on the left is added before the join, so the order of the terms decides the result.

let report = 'Total'; report += ': '; report += 3; report += ' items'; console.log(report); console.log('typeof:', typeof report); const parts = []; for (let i = 1; i <= 3; i += 1) { parts.push('row ' + i); } console.log(parts.join('; '));

node concat.js

Total: 3 items
typeof: string
row 1; row 2; row 3

The accumulator stayed a string from the first append, because the first append already made it one. A loop that appends to a string with += is fine for a handful of pieces and wasteful for thousands, where the array and one join at the end is the shape a program wants. The rest of this lesson is the methods that make each piece the right width.

repeat, padStart and padEnd

repeat repeats a string a given number of times and throws a RangeError for a negative count. padStart and padEnd bring a string up to a width by adding a fill string at one end, and they return the string unchanged when it is already that long. The program shows the error as well, caught and printed.

console.log('repeat:', 'ab'.repeat(3)); console.log('repeat zero is empty:', 'ab'.repeat(0) === ''); console.log('padded:', '42'.padStart(5, '0')); console.log('padded end:', '42'.padEnd(5, '.')); console.log('already longer:', '12345678'.padStart(4, '0')); console.log('spaces:', '[' + 'name'.padStart(8) + ']'); try { console.log('x'.repeat(-1)); } catch (error) { console.log(error.name + ': ' + error.message); }

node pad.js

repeat: ababab
repeat zero is empty: true
padded: 00042
padded end: 42...
already longer: 12345678
spaces: [ name]
RangeError: Invalid count value: -1

The default fill of a pad is a space, which is why the bracket line came out with four spaces inside. The padded number is a string, so a program that pads an invoice number keeps it as text and converts it only if it has to compute with it. The last line is the count a loop produces when its end is smaller than its start, and the message names the value rather than the call.

trim and the case methods

A value typed into a form usually carries spaces at the ends. trim removes them, and trimStart and trimEnd remove one side. The method strips every whitespace character the language knows, including the tab and the newline, and the length of the string is the check that shows what it did. The case methods are the other half of normalising input.

const raw = ' Hello World '; console.log('length:', raw.length); console.log('trim:', '[' + raw.trim() + ']'); console.log('trimStart:', '[' + raw.trimStart() + ']'); console.log('trimEnd:', '[' + raw.trimEnd() + ']'); console.log('upper:', raw.trim().toUpperCase()); console.log('lower:', raw.trim().toLowerCase()); console.log('length after trim:', raw.trim().length); console.log('trimmed comparison:', raw.trim() === 'Hello World');

node trim.js

length: 15
trim: [Hello World]
trimStart: [Hello World ]
trimEnd: [ Hello World]
upper: HELLO WORLD
lower: hello world
length after trim: 11
trimmed comparison: true

The two lengths differ by four, which is the two spaces at each end, and the comparison against the clean word is true only because the trim came first. A program that compares an email address without trimming and lowering has a bug that shows up on one user in a hundred. The case methods follow the Unicode rules of the runtime, which matters for a few letters such as the Turkish dotless i.

split and join

split turns a string into an array at a separator, and join turns an array back into a string with a separator between the elements. An empty separator splits into characters, a second argument limits the number of pieces, and a separator that is not found gives an array of one element rather than an empty array.

const csv = 'ada,alan,grace'; const names = csv.split(','); console.log('parts:', names.length); console.log('first:', names[0]); console.log('joined:', names.join(' | ')); console.log('characters:', 'abc'.split('').length); console.log('limited:', 'a-b-c-d'.split('-', 2).join('+')); console.log('separator missing:', 'abc'.split(',').length); console.log('empty parts:', 'a,,b'.split(',').length); console.log('back to text:', names.join(','));

node split.js

parts: 3
first: ada
joined: ada | alan | grace
characters: 3
limited: a+b
separator missing: 1
empty parts: 3
back to text: ada,alan,grace

The empty separator counts three characters here, and an emoji would count two for one visible character, which is the next lesson. The two middle lines are the ones that decide how careful a parser has to be: a separator that is absent gives one piece, while two separators in a row give an empty piece that a program reading numbers has to handle.

Exercises

  1. Append a number before the text in concat.js, as in report += 3 + ' x'. Which value arrives, and why is it not what the current program prints?
  2. Call 'ab'.repeat(2.5) and 'ab'.padStart(3.5, '0'). Which values arrive, and how does the runtime treat the fraction?
  3. Print '42'.padStart(5, 'ab'). Which fill does the result use, and why does the fill stop where it does?
  4. Trim a string that contains a tab and a newline at its ends. Does trim remove them, and what does length show before and after?
  5. Split '2024-05-17' at the dash and join the pieces with a dot. Which order do the pieces have, and what does the result look like?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does this program print? console.log('ab'.repeat(3));

    Answer

    ababab

    repeat writes the string as many times as the count says, one after another.

  2. What does this program print? console.log('42'.padStart(5, '0'));

    Answer

    00042

    The string is two characters long and the target width is five, so three zeros go in front.

  3. What does this program print? console.log('12345678'.padStart(4, '0'));

    Answer

    12345678

    The string is already wider than the target, so the method returns it unchanged.

  4. What does 'x'.repeat(-1) do?

    Answer

    It throws a RangeError about the count

    A negative count is invalid, and the message names the value that was passed.

  5. What does this program print? console.log('[' + ' hi '.trim() + ']');

    Answer

    [hi]

    trim removes the whitespace at both ends, and the brackets stay where they were.

  6. What does this program print? console.log('a,b,c'.split(',').length);

    Answer

    3

    Two separators divide the string into three pieces.

  7. What does this program print? console.log('abc'.split(',').length);

    Answer

    1

    A separator that is not found leaves one piece, which is the whole string.

  8. What does this program print? console.log(['a', 'b'].join('-'));

    Answer

    a-b

    join writes the separator between the elements and nothing at the ends.

  9. What does this program print? console.log('a,,b'.split(',').length);

    Answer

    3

    Two separators in a row produce an empty piece between them.

  10. Which operation needs an array in the middle?

    Answer

    Split a row into fields, change some fields and join them again

    split and join are the two ends of the array shape, and the other three work on one string.

The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev