JavaScript - How to Replace Multiple Spaces with a Single Space?
Here are the various methods to replace multiple spaces with a single space in JavaScript.
1. Using replace() Method with Regular Expression (Most Common)
The replace() method combined with a regular expression is the most efficient way to replace multiple spaces with a single space.
const s1 = "This is a test string.";
const s2 = s1.replace(/\s+/g, " ");
console.log(s2);
Output
This is a test string.
- \s+: Matches one or more consecutive whitespace characters (spaces, tabs, newlines).
- g flag: Ensures the replacement is applied globally.
- " ": Replaces matches with a single space.
2. Using trim(), split(), and join() Methods
This approach involves splitting the string into an array of words and then joining them back together with a single space.
const s1 = " This is a test string. ";
const s2 = s1.trim().split(/\s+/).join(" ");
console.log(s2);
Output
This is a test string.
- trim(): Removes leading and trailing spaces.
- split(/\s+/): Splits the string into an array of words using one or more spaces as the delimiter.
- join(" "): Joins the array back into a single string with a single space between each word.
3. Using Regular Expression with replace() and trim() Methods
For strings that may have leading or trailing spaces, combining trim() with a regular expression will be a better option
const s1 = " This is a test string. ";
const s2 = s1.trim().replace(/\s+/g, " ");
console.log(s2);
Output
This is a test string.
- trim(): Removes extra spaces at the beginning and end of the string.
- replace(/\s+/g, " "): Replaces multiple spaces within the string.
4. Using a Loop and Conditional Logic
If you want full control over the replacement process, you can use a loop to process the string manually.
const s1 = "This is a test string.";
let s2 = "";
let wasSpace = false;
for (let char of s1) {
if (char === " ") {
if (!wasSpace) {
s2 += char;
wasSpace = true;
}
} else {
s2 += char;
// Reset the flag when a non-space character is found
wasSpace = false;
}
}
console.log(s2);
Output
This is a test string.
- The loop iterates through each character.
- A flag (wasSpace) ensures that consecutive spaces are replaced by a single space.
The replace() method with a regular expression is the most efficient and commonly used approach to replace multiple spaces with a single space. For advanced cleanup, you can combine trim(), split(), and join().