[英]How can i replace all '\' and '/' characters, in a string to '-', in javascript
我有以下javascript。
window.location.href = _searchUrl + query.replace(/\s+/g, '+')
.replace('/', '-')
.replace('\\','-')
這將用+
替換所有空格,只用第一個\\
和第一個/
用-
替換。
我需要讓它替換所有\\
和/
與-
有什么建議么? 或者這應該是URLEncoded?
嘗試:
query.replace(/\s+/g, '+').replace(/[/\\]/g, '-')
第一個正則表達式替換所有空格,因為它具有“g”修飾符。
你需要另外兩個'替換'
你基本上是在做URI編碼的一個子集。 根據需要使用encodeURI()
或encodeURIComponent()
。 請參閱比較escape(),encodeURI()和encodeURIComponent() (不推薦使用escape())。
假設_searchUrl
是這樣的
http://mysite.com/search?q=
那么你應該這樣做:
window.location.href = _searchUrl + encodeURIComponent(query);
沒有必要(或理由)使用正則表達式重新發明(部分)URI編碼規則。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.