Removing All Spaces From a String Using Javascript

I recently wrote about how to remove all occurences of a character from a string using JavaScript by combining the replace() function and a regular expression. This works great but a problem arises when we use this method to try and replace all occurrences of a space.

Using the previously described method you might think we would do something like so:

By doing this however your string will remain unchanged and those pesky spaces still included. Instead, we need to use regular expressions again and look for the spaces using ‘\s’. Our code should therefore look like this:

So there we have it; all spaces stripped from the string. Remember that you could also replace the spaces with another character by changing the second parameter of the replace() function. Let me give you a quick example: