对要发送到web服务器的查询字符串进行编码时-何时使用escape(),何时使用encodeURI()或encodeURIComponent():

使用转义符:

escape("% +&=");

OR

使用encodeURI()/encodeURIComponent()

encodeURI("http://www.google.com?var1=value1&var2=value2");

encodeURIComponent("var1=value1&var2=value2");

当前回答

我觉得这篇文章很有启发性:Javascript疯狂:查询字符串解析

当我试图解释为什么decodeURIComponent不能正确解码“+”时,我发现了这一点。以下是摘录:

String:                         "A + B"
Expected Query String Encoding: "A+%2B+B"
escape("A + B") =               "A%20+%20B"     Wrong!
encodeURI("A + B") =            "A%20+%20B"     Wrong!
encodeURIComponent("A + B") =   "A%20%2B%20B"   Acceptable, but strange

Encoded String:                 "A+%2B+B"
Expected Decoding:              "A + B"
unescape("A+%2B+B") =           "A+++B"       Wrong!
decodeURI("A+%2B+B") =          "A+++B"       Wrong!
decodeURIComponent("A+%2B+B") = "A+++B"       Wrong!

其他回答

我觉得这篇文章很有启发性:Javascript疯狂:查询字符串解析

当我试图解释为什么decodeURIComponent不能正确解码“+”时,我发现了这一点。以下是摘录:

String:                         "A + B"
Expected Query String Encoding: "A+%2B+B"
escape("A + B") =               "A%20+%20B"     Wrong!
encodeURI("A + B") =            "A%20+%20B"     Wrong!
encodeURIComponent("A + B") =   "A%20%2B%20B"   Acceptable, but strange

Encoded String:                 "A+%2B+B"
Expected Decoding:              "A + B"
unescape("A+%2B+B") =           "A+++B"       Wrong!
decodeURI("A+%2B+B") =          "A+++B"       Wrong!
decodeURIComponent("A+%2B+B") = "A+++B"       Wrong!

我发现,即使在很好地掌握了各种方法的用途和功能之后,尝试各种方法也是一种很好的理智检查。

为此,我发现这个网站非常有用,可以证实我的怀疑,即我正在做一些适当的事情。它还被证明对解码encodeURIComponented字符串非常有用,这对解释来说可能相当困难。一个很棒的书签:

http://www.the-art-of-web.com/javascript/escape/

encodeURI()和encodeURIComponent()之间的差异正好是由encodeURIComponent编码的11个字符,而不是由encodeURI编码的:

我在GoogleChrome中使用console.table轻松生成了这个表,代码如下:

var arr=[];对于(变量i=0;i<256;i++){var char=字符串.fromCharCode(i);如果(encodeURI(char)==encodeURIComponent(字符)){arr.push({字符:char,encodeURI:encodeURI(char),encodeURIComponent:encodeURIComponent(char)});}}控制台.桌子(arr);

为了编码,javascript提供了三个内置函数-

escape()-不编码@*/+此方法在ECMA 3之后被弃用,因此应避免使用。encodeURI()-不编码~@#$&*()=:/,;?+'它假定URI是一个完整的URI,因此不会对URI中具有特殊含义的保留字符进行编码。当意图转换完整的URL而不是URL的某个特殊段时,使用此方法。示例-encodeURI('http://stackoverflow.com');将给出-http://stackoverflow.comencodeURIComponent()-不编码-__!~*'( )此函数通过用表示字符UTF-8编码的一个、两个、三个或四个转义序列替换某些字符的每个实例来编码统一资源标识符(URI)组件。此方法应用于转换URL的组件。例如,需要附加一些用户输入示例-encodeURIComponent('http://stackoverflow.com');将提供-http%3A%2F%2Stackoverflow.com

所有这些编码都在UTF 8中执行,即字符将转换为UTF-8格式。

encodeURIComponent与encodeURI的不同之处在于它编码保留字符和encodeURI中的数字符号#

encodeURI()-escape()函数用于javascript转义,而不是HTTP。