In this blog post you’ll learn how to replace multiple spaces of a string with a single space using javascript.
Replace Multiple Spaces With Single Space Using JavaScript.
We’ll see 3 examples for replacing multiple spaces in a string with a single space.
Example 1.
First, we'll split the string into an array by using spaces as delimiters. Then, we'll iterate through each element in the array using a for loop. Within the loop, we'll check if the element is empty or not. If it's not empty, we'll append it to a variable with single space.
JavaScript
// Example 1
let string = " Hello welcome to maketechstuff.com ";
let output = "";
let split = string.split(" ");
for (let i = 0; i < split.length; i++) {
const element = split[i];
if (element === "") {
} else {
output += " " + element;
}
}
console.log(output.trim());
Output:
Example 2.
You can use combination of trim() and replace() method to replace multiple spaces with a single space (e.g., " " becomes " ").
JavaScript
// Example 2
let string = " Hello welcome to maketechstuff.com ";
let spaces_replaced_string = string.trim().replace(/\s+/g, " ");
console.log(spaces_replaced_string);
Output:
Example 3.
You can replace multiple spaces with single space with trim(), split(), filter(), join() method.
JavaScript
// Example 3
let string = " Hello welcome to maketechstuff.com ";
let output = "";
let array = string.trim().split(" ");
let new_array = array.filter(function (array) { return array })
output = new_array.join(" ")
console.log(output);
Share your thoughts.