JavaScript函数decodeURIComponent和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错误”。
其他回答
因为我有同样的问题,但在这里没有找到答案,我做了一些测试,以弄清楚到底有什么不同。 我这样做是因为我需要某些东西的编码,这与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错误”。
为了解释这两者之间的区别,让我来解释一下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将不会。
URI编码:
encodeURI()方法不编码:
, / ? : @ & = + $ * #
例子
URI: https://my test.asp?name=ståle&car=saab
Encoded URI: https://my%20test.asp?name=st%C3%A5le&car=saab
编码URI组件:
encodeURIComponent()方法还编码:
, / ? : @ & = + $ #
例子
URI: https://my test.asp?name=ståle&car=saab
Encoded URI: https%3A%2F%2Fmy%20test.asp%3Fname%3Dst%C3%A5le%26car%3Dsaab
欲了解更多:W3Schoools.com