[英]How can i replace all '\' and '/' characters, in a string to '-', in javascript
I have the following javascript. 我有以下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?
或者这应该是URLEncoded?
尝试:
query.replace(/\s+/g, '+').replace(/[/\\]/g, '-')
The first regular expression replaces ALL the spaces because it has a 'g' modifier. 第一个正则表达式替换所有空格,因为它具有“g”修饰符。
You need it for the other two 'replaces' 你需要另外两个'替换'
You're basically doing a subset of the URI encoding. 你基本上是在做URI编码的一个子集。 Use
encodeURI()
or encodeURIComponent()
as appropriate. 根据需要使用
encodeURI()
或encodeURIComponent()
。 See Comparing escape(), encodeURI(), and encodeURIComponent() (escape() is deprecated). 请参阅比较escape(),encodeURI()和encodeURIComponent() (不推荐使用escape())。
Assuming _searchUrl
is something like 假设
_searchUrl
是这样的
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. 没有必要(或理由)使用正则表达式重新发明(部分)URI编码规则。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.