views:

70

answers:

3

Hi folks,

I have the following javascript.

window.location.href = _searchUrl + query.replace(/\s+/g, '+')
                                         .replace('/', '-')
                                         .replace('\\','-')

this replaces all spaces with + and only the first \ and first / with a -.

i need to make it replace ALL \ and / with a -

Any suggestions? or should this be URLEncoded?

+3  A: 

Try:

query.replace(/\s+/g, '+').replace(/[/\\]/g, '-')
Roatin Marth
I'd simply use `/[\/\\]/g`
Matthew Scharley
@Matthew: sweeter indeed.
Roatin Marth
Initially i was hoping to use some EncodeURI stuff (as cletus posted) but because i'm trying to create a dynamic RESTful url, i think i need to stick with REGEX, it seems.
Pure.Krome
A: 

The first regular expression replaces ALL the spaces because it has a 'g' modifier.

You need it for the other two 'replaces'

pavium
+1  A: 

You're basically doing a subset of the URI encoding. Use encodeURI() or encodeURIComponent() as appropriate. See Comparing escape(), encodeURI(), and encodeURIComponent() (escape() is deprecated).

Assuming _searchUrl is something like

http://mysite.com/search?q=

then you should do this:

window.location.href = _searchUrl + encodeURIComponent(query);

There is no need (or reason) to reinvent (partially) URI encoding rules with regular expressions.

cletus
Hmm. i thought this might be the case, which was why i suggested that in my opening post. The reason why i need this is becuase of dynamic RESTful urls. So i tried that and got this url => /search/23%2F24%2F5%2F6%2F2 foo ... which doesn't work :( Looks like i'll have to stick with REGEX then...
Pure.Krome