Remove Extra Spaces From a String in JavaScript or Node.js

JavaScript comes with a globally available String class. It provides dozens of useful methods for string transformations. For example, you may lowercase or uppercase a given string, replace parts of the string value, or check whether a string value includes a given term.

This tutorial shows you how to remove extra spaces from a string. Removing extra spaces results in a string value where words are separated by a single space.

Node.js Series Overview

Remove Extra Spaces From a String

Use JavaScript’s string.replace() method with a regular expression to remove extra spaces. The dedicated RegEx to match any whitespace character is \s. Expand the whitespace selection from a single space to multiple using the \s+ RegEx.

Combine the string.replace() method and the RegEx and replace it with a single string. Notice the starting and ending spaces will be kept and stripped down to a single space. Trim any surrounding spaces from the string using JavaScript’s string.trim() method:

const sentence = '    My string with a    lot   of Whitespace.  '.replace(/\s+/g, ' ').trim()

// 'My string with a lot of Whitespace.'

Here’s a short overview of what the regular expression does:

  • \s: matches any whitespace symbol: spaces, tabs, and line breaks
  • +: match one or more of the preceding tokens (referencing \s)
  • g: the g at the end indicates iterative searching throughout the full string

That’s it!

Explore the Library

Find interesting tutorials and solutions for your problems.