JavaScript函数decodeURIComponent和decodeURI有什么区别?
当前回答
为了解释这两者之间的区别,让我来解释一下encodeURI和encodeURIComponent之间的区别。
主要区别在于:
encodeURI函数用于完整的URI。 encodeURIComponent函数用于..嗯. .URI组件 位于隔板之间的任何部分(;/ ?: @ & = + $, #)。
因此,在encodeURIComponent中,这些分隔符也被编码,因为它们被视为文本而不是特殊字符。
现在回到decode函数之间的区别,每个函数都解码由对应的encode对应方生成的字符串,负责特殊字符的语义及其处理。
其他回答
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额外编码冒号、斜杠和加号字符,并用于查询字符串。+和?和&在这里特别重要,因为它们是查询字符串中的特殊字符。
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
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
encodeURIComponent/decodeURIComponent()几乎总是您想要使用的对,用于在URI部分中连接和分离文本字符串。
encodeURI不太常见,而且名字很容易误导人:它应该被称为fixBrokenURI。它取一些接近URI,但其中包含无效字符(如空格)的内容,并将其转换为真正的URI。它可以有效地修复来自用户输入的无效URI,还可以用于将IRI(包含纯Unicode字符的URI)转换为普通URI(使用%-转义的UTF-8对非ascii进行编码)。
encodeURI应该被命名为fixBrokenURI(), decodeURI()也可以被命名为potentiallyBreakMyPreviouslyWorkingURI()。我想不出它在任何地方有什么正当用途;避免的。