JavaScript encodeURIComponent 带反斜杠

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13567894/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 19:10:15  来源:igfitidea点击:

JavaScript encodeURIComponent With Backslash

javascriptencoding

提问by Kevin Meredith

w3schoolssays the following about encodeURIComponentfunction:

w3schools关于encodeURIComponent函数的说明如下:

This function encodes special characters. In addition, it encodes the following characters: , / ? : @ & = + $ #.

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

Does that mean that it cannot encode a backslash (\)?

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

回答by zzzzBov

This function encodes special characters. In addition, it encodes the following characters: , / ? : @ & = + $ # .

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

This definition is vague as to what "special characters" are. It sounds like a comparison between encodeURIand encodeURIComponent. Both will correctly escape \as %5C, so you don't have to worry about backslashes.

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

encodeURIwill leave the listed characters as it is assumed that the entire URI is being encoded:

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

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

encodeURIComponentwill escape everythingas it is assumed that the string is to be used as part of a query-string:

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"