replacing spaces in a string with hyphens
Asked Answered
I

3

12

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.

Ingress answered 22/5, 2012 at 16:12 Comment(0)
F
21

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, "-");
Fistulous answered 22/5, 2012 at 16:14 Comment(3)
@Tamil - I don't understand your comment. The OP clearly didn't know about global regex replace so I was educating them on that and showing them how it works which is all in the spirit of SO and to the benefit of future viewers). In addition I offered an improvement idea that would prevent multiple dashes in a row. How do you think this question should have been answered?Fistulous
@Fistulous I'm sorry if I had put up something wrong but You could have asked him if he had tried anything till now on the same OP. Else from here he would think of SO the next moment he thinks of a problem rather trying to solve it.Embosser
@Embosser - I understand that point, but in this case, it was clear that the OP could only think of a recursive function that would replace one space at a time (that's what they were thinking of trying), but the OP thought there must be something better available so was asking for ideas on that. In that sense, this seemed like a fair question to me.Fistulous
P
9

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

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

a becomes

"asd-asd-sad"
Pronominal answered 22/5, 2012 at 16:15 Comment(0)
R
4

Try

value = value.split(' ').join('-');

I used this to get rid of my spaces. Instead of the hyphen I made it empty and works great. Also it is all JS. .split(limiter) will delete the limiter and puts the string pieces in an array (with no limiter elements) then you can join the array with the hyphens.

Rico answered 22/5, 2012 at 18:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.