I have the following javascript.
window.location.href = _searchUrl + query.replace(/\s+/g, '+')
.replace('/', '-')
.replace('\\','-')
this replaces all spaces with + and only 开发者_如何学Gothe first \ and first / with a -.
i need to make it replace ALL \ and / with a -
Any suggestions? or should this be URLEncoded?
Try:
query.replace(/\s+/g, '+').replace(/[/\\]/g, '-')
The first regular expression replaces ALL the spaces because it has a 'g' modifier.
You need it for the other two 'replaces'
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.
加载中,请稍侯......
精彩评论