replacing spaces in a string with hyphens

Nic Meiring picture Nic Meiring · May 22, 2012 · Viewed 13.5k times · Source

I have a string and I need to fix it in order to append it to a query.

Say I have the string "A Basket For Every Occasion" and I want it to be "A-Basket-For-Every-Occasion"

I need to find a space and replace it with a hyphen. Then, I need to check if there is another space in the string. If not, return the fixed string. If so, run the same process again.

Sounds like a recursive function to me but I am not sure how to set it up. Any help would be greatly appreciated.

Answer

jfriend00 picture jfriend00 · May 22, 2012

You can use a regex replacement like this:

var str = "A Basket For Every Occasion";
str = str.replace(/\s/g, "-");

The "g" flag in the regex will cause all spaces to get replaced.


You may want to collapse multiple spaces to a single hyphen so you don't end up with multiple dashes in a row. That would look like this:

var str = "A Basket For Every Occasion";
str = str.replace(/\s+/g, "-");