开发者

How can i replace all '\' and '/' characters, in a string to '-', in javascript

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜