Removing All Spaces From a String Using Javascript

October 20th, 2010 - Posted by Steve Marks to Javascript / jQuery, Web Development.

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:

var str = "B I O S T A L L"
str = str.replace(/ /g,'');
// Outputs 'B I O S T A L L'

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:

var str = "B I O S T A L L"
str = str.replace(/\s/g,'');
// Outputs 'BIOSTALL'

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:

var str = "B I O S T A L L"
str = str.replace(/\s/g,'-');
// Outputs 'B-I-O-S-T-A-L-L'
This entry was posted on Wednesday, October 20th, 2010 at 6:57 pm by +Steve Marks and is filed under Javascript / jQuery, Web Development. You can follow any responses to this entry through the RSS 2.0 feed.

Fear not, we won't publish this

Comments (1)
  1. Hoang says:

    thanks for tips