在JavaScript编码URL不编码&

问题描述 投票:1回答:6

我编码在javascript以下字符串

encodeURI = "?qry=M & L";

这给我一个输出

qry=m%20&%20l

所以,“&”从M & L是没有得到编码。我该怎么办?

javascript url-encoding
6个回答
1
投票

不编码有一个URI具有特殊意义(保留字符)的字符。下面的例子显示了所有一个URI“方案”可以包含可能的部件。

Reference

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 - _ . ! ~ * ' ( )

1
投票

使用encoreURIComponent代替编码let uri = "?qry=M & L" console.log(encodeURIComponent(uri))&如下所示。但它也编码其他特殊字符像%26?

=

1
投票

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方法,但是,确实这些字符进行编码


0
投票

您应该使用encodeURIComponent方法(),而不是是encodeURI()

注:通常encodeURIComponent方法()来编码字符串(查询字符串),将被投入到URL。如果您使用的是现有的网址进行编码,然后你可以使用是encodeURI()

MDN

参考:const uri = "?qry=M & L"; console.log(encodeURIComponent(uri));



-1
投票

escape(str) will not encode: * @ - _ + . / encodeURI(uri) will not encode: ~!@#$&*()=:/,;?+' encodeURIComponent(uri) will not encode: ~!*()'

使用encodeURI()函数用于编码一个URI。

该功能将特殊字符编码,除非:,/? :@&= + $#(使用here编码这些字符)。

而且,还看到encodeURIComponent()

所以,你可能必须做一些像

this answer

希望这可以帮助!干杯!

© www.soinside.com 2019 - 2024. All rights reserved.