Open In App

How to replace multiple spaces with single space in JavaScript ?

Improve
Improve
Like Article
Like
Save
Share
Report

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:

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.

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

Javascript




// String containing multiple spaces
let str = "   Welcome    to   Geeks    for   Geeks   ";
 
// Remove multiple spaces with single space
let newStr = str.replace(/\s+/g, ' ');
 
// Display the result
console.log(newStr);


Output

 Welcome to Geeks for Geeks 

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.

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

Last Updated : 07 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads