我正在用javascript编码以下字符串
encodeURI = "?qry=M & L";
这给我输出
qry=m%20&%20l
因此M & L
中的“&”未得到编码。我该怎么办?
答案 0 :(得分:1)
不对具有特殊含义的字符进行编码(保留 字符)。以下示例显示了所有 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))
答案 1 :(得分:1)
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 请求,例如XMLHTTPRequests,因为“&”,“ +”和“ =”是 未编码,在GET和POST中被视为特殊字符 要求。 encodeURIComponent,但是确实对这些字符进行了编码
答案 2 :(得分:1)
使用encoreURIComponent代替,将&
编码为%26
,如下所示。
但它也编码其他特殊字符,例如?
和=
let uri = "?qry=M & L"
console.log(encodeURIComponent(uri))
答案 3 :(得分:0)
来自here
encodeURI()函数用于对URI进行编码。
此函数对特殊字符进行编码,除了:,/? :@&= + $#(使用encodeURIComponent()
编码这些字符)。
此外,还请参见this answer
因此,您可能必须做类似
的操作var inputWithSplChars = "M & L";
encodeURI = "?qry=" + encodeURIComponent(inputWithSplChars);
希望这会有所帮助!干杯!
答案 4 :(得分:0)
您应该使用encodeURIComponent()而不是encodeURI()
注意:通常,encodeURIComponent()用于对字符串(查询字符串)进行编码,该字符串将被放入URL中。如果您使用现有的URL进行编码,则可以使用encodeURI()
const uri = "?qry=M & L";
console.log(encodeURIComponent(uri));
参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
答案 5 :(得分:0)
此处参考:url encode 您有三种选择:
escape(str) will not encode: * @ - _ + . /
encodeURI(uri) will not encode: ~!@#$&*()=:/,;?+'
encodeURIComponent(uri) will not encode: ~!*()'