Sling Academy
Home/JavaScript/JavaScript: Remove Multiple Consecutive White Spaces

JavaScript: Remove Multiple Consecutive White Spaces

Last updated: June 17, 2023

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.

Next Article: JavaScript: Get filename & file extension from a URL

Previous Article: JavaScript: Convert String to Hex and Vice Versa

Series: JavaScript Strings

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration