JavaScript函数decodeURIComponent和decodeURI有什么区别?


当前回答

decodeURIComponent将解码URI的特殊标记,如&,?,#等,decodeURI将不会。

其他回答

decodeURIComponent将解码URI的特殊标记,如&,?,#等,decodeURI将不会。

js> s = "http://www.example.com/string with + and ? and & and spaces";
http://www.example.com/string with + and ? and & and spaces
js> encodeURI(s)
http://www.example.com/string%20with%20+%20and%20?%20and%20&%20and%20spaces
js> encodeURIComponent(s)
http%3A%2F%2Fwww.example.com%2Fstring%20with%20%2B%20and%20%3F%20and%20%26%20and%20spaces

看起来,encodeURI通过编码空格和其他一些(例如,不可打印的)字符来生成一个“安全”的URI,而encodeURIComponent额外编码冒号、斜杠和加号字符,并用于查询字符串。+和?和&在这里特别重要,因为它们是查询字符串中的特殊字符。

为了解释这两者之间的区别,让我来解释一下encodeURI和encodeURIComponent之间的区别。

主要区别在于:

encodeURI函数用于完整的URI。 encodeURIComponent函数用于..嗯. .URI组件 位于隔板之间的任何部分(;/ ?: @ & = + $, #)。

因此,在encodeURIComponent中,这些分隔符也被编码,因为它们被视为文本而不是特殊字符。

现在回到decode函数之间的区别,每个函数都解码由对应的encode对应方生成的字符串,负责特殊字符的语义及其处理。

encodeURIComponent () 将输入转换为url编码 字符串 encodeURI () url编码输入,但是 假设给出了完整的URL,那么 通过不编码返回一个有效的URL 协议(例如:http://)和 主机名(例如: www.stackoverflow.com)。

decodeURIComponent()和decodeURI()与上面的相反

encodeURIComponent 不逃了出来:

A-Z a-z 0-9 - _ . ! ~ * ' ( )

encodeURI () 不逃了出来:

A-Z a-z 0-9 ; , / ? : @ & = + $ - _ . ! ~ * ' ( ) #

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI