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


当前回答

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

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

主要区别在于:

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

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

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

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额外编码冒号、斜杠和加号字符,并用于查询字符串。+和?和&在这里特别重要,因为它们是查询字符串中的特殊字符。

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

因为我有同样的问题,但在这里没有找到答案,我做了一些测试,以弄清楚到底有什么不同。 我这样做是因为我需要某些东西的编码,这与URL/URI无关。

encodeURIComponent("A")返回"A",它不将"A"编码为"%41" decodeURIComponent("%41")返回"A"。 encodeURI("A")返回"A",它不将"A"编码为"%41" decodeURI("%41")返回"A"。

这意味着两者都可以解码字母数字字符,即使他们没有编码它们。然而……

encodeURIComponent("&")返回"%26"。 decodeURIComponent("%26")返回"&"。 encodeURI("&")返回"&"。 返回“%26”。

尽管encodeURIComponent不编码所有字符,但decodeURIComponent可以解码%00到%7F之间的任何值。

注意:如果您尝试解码%7F以上的值(除非它是unicode值),那么您的脚本将失败,并报出“URI错误”。