我编码在javascript以下字符串
encodeURI = "?qry=M & L";
这给我一个输出
qry=m%20&%20l
所以,“&”从M & L
是没有得到编码。我该怎么办?
不编码有一个URI具有特殊意义(保留字符)的字符。下面的例子显示了所有一个URI“方案”可以包含可能的部件。
qazxsw POI不会编码下列特殊字符
encodeURI
A-Z a-z 0-9 ; , / ? : @ & = + $ - _ . ! ~ * ' ( ) #
所以,你可以使用let uri = "?qry=M & L"
console.log(encodeURI(uri))
,这将编码这些以外所有的字符
encodeURIComponent
A-Z a-z 0-9 - _ . ! ~ * ' ( )
使用encoreURIComponent代替编码let uri = "?qry=M & L"
console.log(encodeURIComponent(uri))
如&
如下所示。但它也编码其他特殊字符像%26
和?
=
该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 - _ . ! ~ * ' ( )
注意这两种方法之间的差异用于编码URL时。
console.log(encodeURIComponent("?qry=M & L"));
从const URL = "https://www.example.com/resource?query=10&id=20&name=hello%"
console.log(encodeURI(URL));
console.log(encodeURIComponent(URL));
:
注意,是encodeURI本身不能形成适当的HTTP GET和POST请求,诸如对XmlHttpRequests,因为“&”,“+”和“=”不进行编码,这被视为在GET和POST请求的特殊字符。 encodeURIComponent方法,但是,确实这些字符进行编码
您应该使用encodeURIComponent方法(),而不是是encodeURI()
注:通常encodeURIComponent方法()来编码字符串(查询字符串),将被投入到URL。如果您使用的是现有的网址进行编码,然后你可以使用是encodeURI()
MDN
参考:const uri = "?qry=M & L";
console.log(encodeURIComponent(uri));
从escape(str) will not encode: * @ - _ + . /
encodeURI(uri) will not encode: ~!@#$&*()=:/,;?+'
encodeURIComponent(uri) will not encode: ~!*()'
使用encodeURI()函数用于编码一个URI。
该功能将特殊字符编码,除非:,/? :@&= + $#(使用here编码这些字符)。
而且,还看到encodeURIComponent()
所以,你可能必须做一些像
this answer
希望这可以帮助!干杯!