Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replacing spaces in a string with hyphens

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.

like image 482
Nic Meiring Avatar asked May 22 '12 16:05

Nic Meiring


1 Answers

Use replace and find for whitespaces \s globally (flag g)

var a = "asd asd sad".replace(/\s/g,"-");

a becomes

"asd-asd-sad"
like image 100
Tiago Peczenyj Avatar answered Oct 12 '22 14:10

Tiago Peczenyj