Open In App

JavaScript Program to Remove All Whitespaces From a Text

In this article, we will be eliminating spaces from a string and will explore the various types of cases that fall under the category of spaces

We will explore all the above approaches with the help of illustration.



Using Regular Expressions (regex)

Regular expressions are powerful tools for pattern matching. They can be used to find and replace white spaces with an empty string or any desired character in a text.

Syntax

const stringWithoutSpaces = stringWithSpaces.replace(/\s/g, '');

Example: This example illustrates the use of the Regular Expressions to filter out all Whitespaces from a Text.






const removeSpaces = (inputText) => {
    return inputText.replace(/\s/g, "");
};
console.log(
    removeSpaces(
        `GeeksforGeeks  is  the  best
      platform  for learning.`
    )
);

Output
GeeksforGeeksisthebestplatformforlearning.

Using String Split and Join

This method can split the text into an array of words based on white space and then join the array elements back together without spaces, effectively removing the white spaces.

Syntax

const stringWithoutSpaces = stringWithSpaces.split(' ').join('');

Example: This example illustrates the use of the String Split and Join.




const removeSpaces = (inputText) => {
    const words =
        inputText.split(/\s+/);
    return words.join("");
};
 
console.log(
    removeSpaces(
        `Geeks For Geeks`
    )
);

Output
GeeksForGeeks

Using the ES6 replace() method with a Regular Expression

The replace() method in JavaScript can be used with a regular expression to search for white spaces and replace them with another character or an empty string.

Syntax

const stringWithoutSpaces = stringWithSpaces.replace(/\s+/g, '');

Example: This example illustrates the use of the replace() method with a Regular Expression.




const removeSpaces = (inputText) => {
    return inputText.replace(
        /\s+/g,
        ""
    );
};
console.log(
    removeSpaces("Geeks For Geeks")
);

Output
GeeksForGeeks

Using filter() and join() (functional approach)

This approach involves splitting the text into an array of words and then using the filter() function to remove empty elements (whitespace) from the array. Finally, the join() method is used to combine the remaining elements into a single string.

Syntax

const stringWithoutSpaces = stringWithSpaces.split('').filter(char => char !== ' ').join('');

Example: This example illustrates the use of the filter() and join() Methods.




const removeSpaces = (inputText) => {
    const characters =
        inputText.split("");
    const nonEmptyCharacters =
        characters.filter(
            (char) => !/\s/.test(char)
        );
    return nonEmptyCharacters.join("");
};
 
console.log(
    removeSpaces("Geeks for Geeks")
);

Output
GeeksforGeeks

Article Tags :