JavaScript: Remove Multiple Consecutive White Spaces

Updated: June 17, 2023 By: Wolf Post a comment

When working with text data in JavaScript, there might be cases where you encounter a string that contains multiple consecutive whitespace characters like this:

"Welcome     to Sling  Academy!"

The string above look so weird, and it’s also longer and takes more memory than necessary. Therefore, it is better to replace multiple consecutive whitespace characters with single whitespace characters. This concise, example-based article will walk you through a couple of different ways to do so.

Using regular expressions

This approach uses a regular expression with the replace() method to remove consecutive whitespace characters from a string. The regular expression pattern is as follows:

/ +/g

Code example:

str1 = "Welcome     to Sling  Academy!";
console.log(str1.replace(/ +/g, ' '));

Output:

Welcome to Sling Academy!

You can also define a function if you have to deal with this task many times:

const removeDuplicateWhitespace = (str) => {
  return str.replace(/ +/g, ' ');
};

Using split() and join()

The main idea of this approach is to split the string into an array using whitespace as the delimiter, filter out empty elements, and then join the array back into a string with single spaces. The detailed steps are shown below:

  1. Use the split() method with a whitespace delimiter to split the string into an array of words.
  2. Use the filter() method to remove empty elements from the array.
  3. Use the join() method with a single space separator to join the array back into a string.

Example:

const removeDuplicateWhitespace = (str) => {
  return str
    .split(' ')
    .filter((word) => word !== '')
    .join(' ');
};

// Example usage
const text = 'Welcome   to Sling    Academy!   How    are you?';
const result = removeDuplicateWhitespace(text);
console.log(result);

Output:

Welcome to Sling Academy! How are you?

If your input string has leading and trailing whitespace characters, they will be eliminated all.