Emmanuel Akinfulubi

JavaScriptString

Replace multiple spaces with one in JavaScript

Intermediate · 3 min read

Text that people paste into forms is often messy: double spaces, tabs, line breaks in the middle of a name, spaces at the ends. Before you save it, compare it or show it, you usually want to tidy it so every gap is a single space. That one clean-up step fixes a surprising number of "why don't these match?" bugs.

In this tutorial you will write squish, a one-line function that trims the ends and folds every run of whitespace into one space. Then you will look at one character it changes that you might want to keep: the non-breaking space. You should know trim and the basics of replace. The regex pieces are explained below.

What counts as whitespace

In a regular expression, \s matches any whitespace character: an ordinary space, a tab (\t), a newline (\n) and several less common spaces, including the non-breaking space. Add +, meaning "one or more", and \s+ matches a whole run of whitespace at once, however it is mixed.

Why one replace is enough

replace(/\s+/g, ' ') swaps every run for a single space. The g flag means "every match, not just the first". Because the pattern matches a whole run, three spaces and a tab become one space, not four.

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

62 Compress whitespace to single spaces

fair

Fold every run of whitespace in a block of text down to one space and trim the ends. Then check what it did to a non-breaking space.

Stuck? Three hints, smallest first
  1. 1. One replace with /\s+/g handles spaces, tabs and newlines together.
  2. 2. Trim as well, or a leading run becomes a leading space.
  3. 3. \s includes a non-breaking space, so it gets replaced along with the rest.

Step 1: fold the runs

Step 1

console.log(JSON.stringify('a    b'.replace(/\s+/g, ' ')));      // "a b"
console.log(JSON.stringify('a\t\nb'.replace(/\s+/g, ' ')));      // "a b"
console.log(JSON.stringify('one\n\ntwo'.replace(/\s+/g, ' ')));  // "one two"

JSON.stringify puts quotes round the result so you can see exactly where the spaces are. Tabs and newlines are whitespace too, so a paragraph split across lines folds onto one line.

Step 2: the ends, the natural wrong turn

Step 2

console.log(JSON.stringify('   a b   '.replace(/\s+/g, ' '))); // " a b "

Replacing alone turns the leading run into one leading space and the trailing run into one trailing space. They are still there. ' a b ' and 'a b' would not be equal.

Step 3: trim as well

Step 3

const squish = (text) => text.trim().replace(/\s+/g, ' ');
console.log(JSON.stringify(squish('   a b   ')));         // "a b"
console.log(JSON.stringify(squish('a    b')));           // "a b"
console.log(squish('one\n\ntwo\n\nthree'));               // 'one two three'
console.log(squish('a b c'));                             // 'a b c'
console.log(JSON.stringify(squish(' \t\n ')));            // ""

trim() removes whitespace from both ends first, then replace folds what is left in the middle. Text that is already tidy comes out unchanged. Text that is only whitespace becomes an empty string.

Step 4: does the order matter?

Step 4

const squish = (text) => text.trim().replace(/\s+/g, ' ');
console.log('a  b '.replace(/\s+/g, ' ').trim() === squish('a  b ')); // true

No. Trimming first or last gives the same result. Trimming first means slightly less text for replace to walk through, but either way is fine.

Step 5: the non-breaking space

A non-breaking space looks like a normal space but tells the browser "never break the line here". It is written \u00a0 in a string. It keeps things like 10 kg or Fig. 3 together so the number and its unit never end up on different lines.

\s includes it, so squish replaces it with an ordinary space:

Step 5

const squish = (text) => text.trim().replace(/\s+/g, ' ');
const text = 'a\u00a0b';
console.log(squish(text) === 'a b');         // true
console.log(squish(text).includes('\u00a0')); // false

For tidying a username or a search term, that is what you want. For text where the non-breaking space was put there on purpose, it is lost, and the two parts can now wrap onto separate lines.

Step 6: keep it with an explicit list

If you only want to fold ordinary spaces, tabs and newlines, list them yourself instead of using \s:

Step 6

const text = 'a\u00a0b';
const folded = text.replace(/[ \t\n]+/g, ' ');
console.log(folded === text); // true

[ \t\n] means "a space, a tab or a newline" and nothing else, so the non-breaking space is left alone.

The full solution

The panel has squish and prints four examples, including a paragraph with blank lines and the non-breaking space. Press Run, then read the checks underneath.

The answer

const squish = (text) => text.trim().replace(/\s+/g, ' ');

console.log("squish('a    b')          :", JSON.stringify(squish('a    b')));
console.log("squish('   a b   ')       :", JSON.stringify(squish('   a b   ')));
console.log("squish('one\\n\\ntwo')     :", JSON.stringify(squish('one\n\ntwo')));
console.log('a non-breaking space is replaced too:', JSON.stringify(squish('a\u00a0b')));

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('a run of spaces becomes one', squish('a    b'), 'a b');
test('leading and trailing whitespace goes', squish('   a b   '), 'a b');
test('tabs and newlines are whitespace too', squish('a\t\nb'), 'a b');
test('a paragraph folds onto one line', squish('one\n\ntwo\n\nthree'), 'one two three');
test('already-tidy text is unchanged', squish('a b c'), 'a b c');
test('whitespace-only text becomes empty', squish(' \t\n '), '');
test('a non-breaking space matches \\s, so it is REPLACED', squish('a\u00a0b'), 'a b');
test('and is therefore gone from the result', squish('a\u00a0b').includes('\u00a0'), false);
test('an explicit class is how you keep it', 'a\u00a0b'.replace(/[ \t\n]+/g, ' '), 'a\u00a0b');
test('trimming before or after gives the same answer', 'a  b '.replace(/\s+/g, ' ').trim(), squish('a  b '));

Overlaps Regular expressions 12. That one is about the pattern; this one is about the two decisions around it — trim as well as replace, and know what \s includes.

\s covering U+00A0 is usually what you want and occasionally destructive. A non-breaking space is there on purpose: it holds 10 kg or Fig. 3 together across a line break, and squishing turns it into an ordinary space that can wrap. When that matters, list the characters you mean rather than using the shorthand.

Trim first or last makes no difference to the result, as the last assertion shows. Trimming first is marginally cheaper, since there is less text for the replacement to walk.

Common mistakes

  • Replacing without trimming. The ends keep one space each. Call trim() as well.
  • Using / +/g. That only matches ordinary spaces. Tabs and newlines stay. Use \s+.
  • Forgetting the g flag. Only the first run is folded. Add g.

Try it yourself

  1. Write sameText(a, b) that compares two strings after squishing and lowercasing both.
  2. Squish a multi-line address but keep the line breaks, folding only spaces and tabs on each line.
  3. Count how many characters squish removed from a messy string.

Keep practising

Newsletter

New writing, when it lands.

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