简体   繁体   English

如何在javascript中将字符串中的所有'\\'和'/'字符替换为' - '

[英]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.

相关问题 如何在javascript中两个字符之间替换字符串? - How can I replace string between two characters in javascript? 如何替换javascript中字符串的前两个字符? - how can i replace first two characters of a string in javascript? 对于这种特定情况,如何使用 JavaScript 替换字符串中的所有字符:replace 。 经过 _ - How to replace all characters in a string using JavaScript for this specific case: replace . by _ 如何替换字符串中的多个字符? - How can I replace multiple characters in a string? 如何用 javascript 中的新字符串和填充替换字符串的前 5 个字符? - How can I replace first 5 characters of a string with new another string and padding in javascript? Javascript:如何用空格替换字符串中的所有字符? - Javascript : How do you replace all the characters in the string with space? 如何使用 replace() 方法更改 Javascript 中字符串的所有字符? - How to change all characters of a string in Javascript with replace() method? 如何替换字符串中的所有字符? - How to replace all characters in a string? Javascript,如何将注释中的所有空行替换为其他字符 - In Javascript, How can I replace all blank lines in comments with other characters 如何通过 JavaScript function 全局替换字符串中的特殊字符 - How can I replace special characters in a String globally via a JavaScript function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM