[英]encoding url in javascript not encoding &
我在javascript中編碼以下字符串
encodeURI = "?qry=M & L";
這給了我一個輸出
qry=m%20&%20l
因此,來自M & L
的“&”未得到編碼。 我該怎么辦?
不對URI具有特殊含義的字符(保留字符)進行編碼。 以下示例顯示了URI“方案”可能包含的所有部分。
encodeURI
將不對以下特殊字符進行編碼
A-Z a-z 0-9 ; , / ? : @ & = + $ - _ . ! ~ * ' ( ) #
let uri = "?qry=M & L" console.log(encodeURI(uri))
因此,您可以使用encodeURIComponent ,這將對除這些字符以外的所有字符進行編碼
A-Z a-z 0-9 - _ . ! ~ * ' ( )
let uri = "?qry=M & L" console.log(encodeURIComponent(uri))
encodeURI()
不會對&
進行編碼&
因為它將僅對某些特殊字符集進行編碼。 進行編碼&
您需要使用encodeURIComponent
。
encodeURI
所有內容進行編碼,除了:
A-Z a-z 0-9 ; , / ? : @ & = + $ - _ . ! ~ * ' ( ) #
encodeURIComponent
所有內容進行編碼,除了:
A-Z a-z 0-9 - _ . ! ~ * ' ( )
console.log(encodeURIComponent("?qry=M & L"));
請注意,兩種用於編碼URL的方法之間的區別。
const URL = "https://www.example.com/resource?query=10&id=20&name=hello%" console.log(encodeURI(URL)); console.log(encodeURIComponent(URL));
從MDN :
請注意,encodeURI本身無法形成正確的HTTP GET和POST請求,例如對於XMLHTTPRequest,因為未對“&”,“ +”和“ =”進行編碼,它們在GET和POST請求中被視為特殊字符。 encodeURIComponent,但是對這些字符進行編碼
改為使用encoreURIComponent來將&
編碼為%26
,如下所示。 但它也編碼其他特殊字符,如?
和=
let uri = "?qry=M & L" console.log(encodeURIComponent(uri))
您應該使用encodeURIComponent()而不是encodeURI()
注意 :通常,encodeURIComponent()用於對將放入URL的字符串(查詢字符串)進行編碼。 如果您使用現有的URL進行編碼,則可以使用encodeURI()
const uri = "?qry=M & L";
console.log(encodeURIComponent(uri));
參考 : https : //developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
此處參考: url encoding您有三個選擇:
escape(str) will not encode: * @ - _ + . /
encodeURI(uri) will not encode: ~!@#$&*()=:/,;?+'
encodeURIComponent(uri) will not encode: ~!*()'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.