The Wayback Machine - https://web.archive.org/web/20231204044653/https://www.geeksforgeeks.org/how-to-replace-multiple-spaces-with-single-space-in-javascript/
Open In App
Related Articles

How to replace multiple spaces with single space in JavaScript ?

Improve Article
Improve
Save Article
Save
Like Article
Like

In this article, we will see how to replace multiple spaces with a single space in JavaScript.

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

Method 1: Using replace() Method

We will use 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:

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 trim() method to remove extra space from 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:

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



Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 17 Jul, 2023
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials