JavaScript函数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

其他回答

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将不会。

encodeURIComponent/decodeURIComponent()几乎总是您想要使用的对,用于在URI部分中连接和分离文本字符串。

encodeURI不太常见,而且名字很容易误导人:它应该被称为fixBrokenURI。它取一些接近URI,但其中包含无效字符(如空格)的内容,并将其转换为真正的URI。它可以有效地修复来自用户输入的无效URI,还可以用于将IRI(包含纯Unicode字符的URI)转换为普通URI(使用%-转义的UTF-8对非ascii进行编码)。

encodeURI应该被命名为fixBrokenURI(), decodeURI()也可以被命名为potentiallyBreakMyPreviouslyWorkingURI()。我想不出它在任何地方有什么正当用途;避免的。

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

主要区别在于:

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

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

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

因为我有同样的问题,但在这里没有找到答案,我做了一些测试,以弄清楚到底有什么不同。 我这样做是因为我需要某些东西的编码,这与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错误”。