Replacing white space in a string

January 19th, 2011 posted by The Hippy

A handy little tip, if all you need to do is rip out spaces in a string don’t bother with using slice(), use regex instead. Copy the following line of code and replace ‘-’ with whatever you need to replace the space with…

yourString = yourString.replace(/\s+/g, '-');

So for example, if yourString=”blah blah blah”, it will now become “blah-blah-blah”. This is especially useful for amending URLs.

Happy new year!

Post to Twitter Post to Facebook Post to StumbleUpon Post to Digg