How to use trim(), split(), and join() Methods In Javascript

First, we will use the trim() method to remove extra space from the starting and ending, then use the split() method to split the string from spaces and then use the join() method to join the split string using a single space.

Example: This example shows the implementation of the above-explained approach.

Javascript
// String containing multiple spaces
let str = "   Welcome    to   Geeks    for   Geeks   ";

// Replace multiple spaces with single space
let newStr = str.trim().split(/[\s,\t,\n]+/).join(' ');

// Display the result
console.log(newStr);

Output
Welcome to Geeks for Geeks

How to replace multiple spaces with single space in JavaScript ?

In this article, we will see how to replace multiple spaces with a single space in JavaScript. We will have a string having multiple spaces and we need to remove those extra spaces.

There are two methods to replace multiple spaces with a single space in JavaScript:

Table of Content

  • Method 1: Using replace() Method
  • Method 2: Using trim(), split(), and join() Methods
  • Method 3: Using a Regular Expression with replace() Method and Trim()

Similar Reads

Method 1: Using replace() Method

We will use the replace() method to replace multiple spaces with a single space in JavaScript. First, we use the regular expression /\s+/g to match one or more spaces globally in the string and then replace it with the ‘ ‘ value....

Method 2: Using trim(), split(), and join() Methods

First, we will use the trim() method to remove extra space from the starting and ending, then use the split() method to split the string from spaces and then use the join() method to join the split string using a single space....

Method 3: Using a Regular Expression with replace() Method and Trim()

This approach combines the use of regular expressions with the replace() method and trim() method. We first use trim() to remove any leading or trailing whitespace from the string. Then, we use a regular expression to replace consecutive spaces with a single space....