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'
Follow us on Twitter
Subscribe to RSS Feed
No comments have been left yet. Be the first