Replace One, two or Multiple spaces of a String With a Single Space Using JavaScript.

0

In this blog post you’ll learn how to replace multiple spaces of a string with a single space using javascript.


replace many spaces in string or text with a single space


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:


replace multiple spaces with a single space


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:


replace multiple spaces with a single space


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);
  

Output:


replace multiple spaces with a single space


This is how you can replace multiple spaces with a single space in a string or text using JavaScript. Feel free to leave any questions or suggestions in the comments section below.
Tags

Post a Comment

0Comments
Post a Comment (0)
To Top