6

w3schools对功能有以下说明encodeURIComponent

此函数对特殊字符进行编码。此外,它还对以下字符进行编码:, / ? : @ & = + $ #.

这是否意味着它不能对反斜杠 ( \) 进行编码?

4

1 回答 1

16

此函数对特殊字符进行编码。此外,它还对以下字符进行编码:, / ? : @ & = + $ # .

这个定义对于什么是“特殊字符”是模糊的。encodeURI这听起来像是和之间的比较encodeURIComponent。两者都将正确转义\%5C,因此您不必担心反斜杠。

encodeURI将保留列出的字符,因为假定整个 URI 正在被编码:

encodeURI('http://example.com/foo bar/baz.html');
//produces "http://example.com/foo%20bar/baz.html"

encodeURIComponent将转义所有内容,因为假定该字符串将用作查询字符串的一部分:

'http://example.com?foo=' + encodeURIComponent('http://example.com/fizz/buzz.html');
//produces "http://example.com?foo=http%3A%2F%2Fexample.com%2Ffizz%2Fbuzz.html"
于 2012-11-26T15:34:41.150 回答