簡體   English   中英

javascript中的編碼url不編碼&

[英]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: ~!*()'

這里

encodeURI()函數用於對URI進行編碼。

此函數對特殊字符進行編碼,但以下字符除外:,/? :@&= + $#(使用encodeURIComponent()編碼這些字符)。

而且,也看到這個答案

因此,您可能必須做類似的事情

var inputWithSplChars = "M & L";
encodeURI  = "?qry=" + encodeURIComponent(inputWithSplChars);

希望這可以幫助! 干杯!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM