Emmanuel Akinfulubi

JavaScriptString

Word wrap text to a fixed width in JavaScript

Advanced · 4 min read

Terminal programs, plain-text emails, receipt printers and code comments all have a fixed width. Text that runs past it gets cut off or breaks in ugly places. Word wrapping fixes that: it breaks a paragraph into lines no wider than a set number of characters, moving a word to the next line when it won't fit, instead of splitting it.

In this tutorial you will write wrap(text, width), which returns an array of lines. You will see the off-by-one mistake that makes every line one character too wide, and decide what to do with a word that is longer than the whole column. You should know split, push and string length. Everything else is explained as we go.

The greedy plan

Build one line at a time:

  1. Split the text into words.
  2. Take the next word. If adding it to the current line still fits, add it.
  3. If it doesn't fit, finish the current line and start a new one with this word.
  4. At the end, finish the last line.

This is called greedy wrapping, because each line takes as many words as it can before moving on.

The space counts

When you add a word to a line that already has words on it, you also add a space between them. So the line's new length is the old length, plus one for the space, plus the word's length.

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

60 Wrap text to a column width

hard

Break a paragraph into lines no wider than n characters, without splitting a word. Decide what to do with a word that is wider than the column.

Stuck? Three hints, smallest first
  1. 1. Build the current line word by word and start a new one when the next word will not fit.
  2. 2. The fit test has to include the space you are about to add.
  3. 3. A word longer than the column cannot fit anywhere, so either it overflows or you break it deliberately.

Step 1: split into words

Step 1

console.log('The  quick\nbrown'.split(/\s+/)); // [ 'The', 'quick', 'brown' ]
console.log(''.split(/\s+/));                 // [ '' ]
console.log(''.split(/\s+/).filter(Boolean)); // []

/\s+/ splits on any run of whitespace: spaces, tabs or newlines. Splitting an empty string gives one empty word, so filter(Boolean) removes empty strings. That way an empty text gives no words at all.

Step 2: the fit test, the natural wrong turn

A first try often checks only the word's length:

Step 2

function wrapTooWide(text, width) {
  const lines = [];
  let line = '';
  for (const word of text.split(/\s+/).filter(Boolean)) {
    if (line === '') line = word;
    else if (line.length + word.length <= width) line += ' ' + word;
    else { lines.push(line); line = word; }
  }
  if (line !== '') lines.push(line);
  return lines;
}
const lines = wrapTooWide('aaaa bbbbb cc', 9);
console.log(lines);                       // [ 'aaaa bbbbb', 'cc' ]
console.log(lines[0].length);             // 10

aaaa is 4 and bbbbb is 5, which adds up to 9, so the test lets it through. But the line also gets a space, so it is 10 characters, one too wide for a 9-wide column.

Step 3: include the space

Step 3

function wrap(text, width) {
  const lines = [];
  let line = '';
  for (const word of text.split(/\s+/).filter(Boolean)) {
    if (line === '') line = word;
    else if (line.length + 1 + word.length <= width) line += ' ' + word;
    else { lines.push(line); line = word; }
  }
  if (line !== '') lines.push(line);
  return lines;
}
console.log(wrap('aaaa bbbbb cc', 9)); // [ 'aaaa', 'bbbbb cc' ]
const text = 'The quick brown fox jumps over the lazy dog';
console.log(wrap(text, 10)); // [ 'The quick', 'brown fox', 'jumps over', 'the lazy', 'dog' ]
console.log(wrap(text, 20).length); // 3

The + 1 is the space. Now every line fits. The first word on a line always goes on, because a new line has no space before it. jumps over is exactly 10 characters, and <= allows a line that fills the width exactly.

Step 4: check the result

Step 4

function wrap(text, width) {
  const lines = [];
  let line = '';
  for (const word of text.split(/\s+/).filter(Boolean)) {
    if (line === '') line = word;
    else if (line.length + 1 + word.length <= width) line += ' ' + word;
    else { lines.push(line); line = word; }
  }
  if (line !== '') lines.push(line);
  return lines;
}
const text = 'The quick brown fox jumps over the lazy dog';
console.log(wrap(text, 10).every((l) => l.length <= 10)); // true
console.log(wrap(text, 10).join(' ') === text);           // true
console.log(wrap('', 10));                                // []
console.log(wrap('a  b', 10));                            // [ 'a b' ]

Two quick checks prove the function works: no line is too wide, and joining the lines with spaces gives back the original text, so no word was lost or repeated. Runs of spaces become one space, because we split on /\s+/.

Step 5: a word wider than the column

Step 5

function wrap(text, width) {
  const lines = [];
  let line = '';
  for (const word of text.split(/\s+/).filter(Boolean)) {
    if (line === '') line = word;
    else if (line.length + 1 + word.length <= width) line += ' ' + word;
    else { lines.push(line); line = word; }
  }
  if (line !== '') lines.push(line);
  return lines;
}
console.log(wrap('Antidisestablishmentarianism', 10)); // [ 'Antidisestablishmentarianism' ]

A word longer than the column can't fit on any line. Our function puts it on a line of its own and lets it stick out. That keeps the word readable, but it breaks the width. Long web addresses are the usual cause.

Step 6: break it on purpose

If the width must be kept, cut the long word into pieces deliberately:

Step 6

const hardBreak = (word, width) => word.match(new RegExp('.{1,' + width + '}', 'g')) || [];
console.log(hardBreak('Antidisestablishmentarianism', 10)); // [ 'Antidisest', 'ablishment', 'arianism' ]

new RegExp('.{1,10}', 'g') builds the pattern "between 1 and 10 of any character", and with g, match returns every piece. Each piece is as long as possible, so all but the last are exactly 10 wide. The pieces aren't real words, which is the price of a fixed width. Whether to overflow or break is a choice you make for your app.

Lines, not one string

wrap returns an array. To print it, join with a newline: wrap(text, 10).join('\n'). Keeping them separate lets the caller choose the line ending, or add a prefix like // to every line.

The full solution

The panel has wrap and hardBreak, prints the sentence wrapped to 10, and shows the long word both ways. Press Run, then read the checks underneath.

The answer

function wrap(text, width) {
  const lines = [];
  let line = '';
  for (const word of text.split(/\s+/).filter(Boolean)) {
    if (line === '') line = word;                              // first word always goes on
    else if (line.length + 1 + word.length <= width) line += ' ' + word;
    else { lines.push(line); line = word; }
  }
  if (line !== '') lines.push(line);
  return lines;
}

// A word wider than the column has to be cut on purpose, not by accident.
const hardBreak = (word, width) => word.match(new RegExp('.{1,' + width + '}', 'g')) || [];

const line = 'The quick brown fox jumps over the lazy dog';

console.log(wrap(line, 10).join('\n'));
console.log('---');
console.log('at width 20 :', wrap(line, 20).length, 'lines');
console.log('a long word :', wrap('Antidisestablishmentarianism', 10), '<- overflows');
console.log('broken      :', hardBreak('Antidisestablishmentarianism', 10));

Output


      
10 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 10 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

10 checks

test('the paragraph breaks into lines that fit', wrap(line, 10), ['The quick', 'brown fox', 'jumps over', 'the lazy', 'dog']);
test('no line is wider than the column', wrap(line, 10).every((l) => l.length <= 10), true);
test('a line that exactly fills the width is allowed', wrap(line, 10)[2].length, 10);
test('a wider column needs fewer lines', wrap(line, 20).length, 3);
test('an empty text wraps to no lines at all', wrap('', 10), []);
test('runs of whitespace are normalised to one space', wrap('a  b', 10), ['a b']);
test('a word longer than the column OVERFLOWS rather than breaking', wrap('Antidisestablishmentarianism', 10), ['Antidisestablishmentarianism']);
test('breaking it needs a deliberate hard break', hardBreak('Antidisestablishmentarianism', 10), ['Antidisest', 'ablishment', 'arianism']);
test('rendering is a join, and separate from the wrapping', wrap('a b c', 3).join('\n'), 'a b\nc');
test('no word is lost or duplicated', wrap(line, 10).join(' '), line);

The fit test is line.length + 1 + word.length, and the + 1 is the space. Leaving it out gives lines exactly one character too wide, which passes casual inspection and fails against a hard terminal width.

The overflow case is a design decision, not an oversight. Overflowing keeps every word readable and can break a layout; hard-breaking guarantees the width and produces nonsense like 'ablishment'. Long URLs are the case that forces you to choose.

This wrapper also normalises whitespace, because it splits on /\s+/. Double spaces after a full stop and any deliberate alignment in the input are lost. Returning lines rather than a joined string is what keeps the decision about the line ending with the caller.

Common mistakes

  • Leaving out the space in the fit test. Lines come out one character too wide. Test line.length + 1 + word.length.
  • Forgetting the last line. The loop only pushes a line when the next word doesn't fit. Push the final one after the loop.
  • Splitting with split(' '). Double spaces and newlines create empty words. Split on /\s+/ and filter.

Try it yourself

  1. Wrap the sentence to width 15 and print it with join('\n').
  2. Change wrap to call hardBreak on any word wider than the column, so no line is ever too wide.
  3. Add an indent option that puts two spaces in front of every line, still within the width.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.