How to Remove Spaces From String in JavaScript

Removing spaces from a string in JavaScript is a common task for software developers.

This can be achieved through various methods, including using built-in string functions, regular expressions, and custom functions.

In this tutorial, we will explore each of these methods in detail.


Using the Replace Method

The replace method is a built-in JavaScript string function that can be used to replace specified characters with other characters.

To remove spaces from a string, we can use the following code:

let str = "Remove spaces from this string";
str = str.replace(/\s/g, "");
console.log(str); // Output: Removespacesfromthisstring

In the above code, /\s/g is a regular expression that matches any white space character.

The g flag stands for “global,” meaning that all occurrences of the pattern will be replaced.

Using the Split and Join Methods

Another way to remove spaces from a string in JavaScript is to split the string into an array of characters, remove the spaces, and then join the remaining characters back into a single string.

The following code demonstrates this method:

let str = "Remove spaces from this string";
let chars = str.split("");
chars = chars.filter(char => char !== " ");
str = chars.join("");
console.log(str); // Output: Removespacesfromthisstring

In the above code, the split method splits the string into an array of characters.

The filter method then removes all elements that are equal to " " (a space).

Finally, the join method joins the remaining elements back into a single string.

Using a Custom Function

Finally, we can write a custom function to remove spaces from a string in JavaScript. The following code demonstrates this method:

let str = "Remove spaces from this string";

function removeSpaces(str) {
  let result = "";
  for (let i = 0; i < str.length; i++) {
    if (str[i] !== " ") {
      result += str[i];
    }
  }
  return result;
}

str = removeSpaces(str);
console.log(str); // Output: Removespacesfromthisstring

In the above code, the removeSpaces function takes a string as input and iterates over each character.

If a character is not a space, it is added to the result string. The final result is returned from the function.


Conclusion

In conclusion, there are several ways to remove spaces from a string in JavaScript, including using the replace method, the split and join methods, and a custom function.

Each method has its own advantages and disadvantages, and the choice of which method to use will depend on the specific requirements of the task at hand.