什么时候应该使用转义而不是encodeURI / encodeURIComponent?

时间:2020-03-05 18:56:56  来源:igfitidea点击:

在对要发送到Web服务器的查询字符串进行编码时,何时使用escape()以及何时使用encodeURI()或者encodeURIComponent()

使用转义:

escape("% +&=");

或者

使用encodeURI()/ encodeURIComponent()

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

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

解决方案

回答

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

回答

还记得,他们都不同的编码字符集,并选择一个你需要适当。 encodeURI()编码的字符数少于encodeURIComponent()的编码字符数,而encodeURIComponent()的编码字符数少于escape()(并且与dannyp相同)。

回答

不要使用它!
在第B.2.1.2节"转义"中定义了" escape()",并且附件B的引言中说:

... All of the language features and behaviours specified in this annex have one or more undesirable characteristics and in the absence of legacy usage would be removed from this specification. ...

  ... Programmers should not use or assume the existence of these features and behaviours when writing new ECMAScript code....

行为:

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/escape

特殊字符的编码除外:@ * _ +-。/

字符的十六进制形式(其代码单位值为0xFF或者更小)是两位数字的转义序列:%xx。

对于具有更大代码单位的字符,将使用四位数格式"%uxxxx"。查询字符串(在RFC3986中定义)中不允许这样做:

query       = *( pchar / "/" / "?" )
pchar         = unreserved / pct-encoded / sub-delims / ":" / "@"
unreserved    = ALPHA / DIGIT / "-" / "." / "_" / "~"
pct-encoded   = "%" HEXDIG HEXDIG
sub-delims    = "!" / "$" / "&" / "'" / "(" / ")"
              / "*" / "+" / "," / ";" / "="

仅当百分号后跟两个十六进制数字时才允许使用百分号,不允许百分号后接u

当我们需要有效的URL时,请使用encodeURI。拨打电话:

encodeURI("http://www.example.org/a file with spaces.html")

要得到:

http://www.example.org/a%20file%20with%20spaces.html

不要调用encodeURIComponent,因为它会破坏URL并返回

http%3A%2F%2Fwww.example.org%2Fa%20file%20with%20spaces.html

当我们想对URL参数的值进行编码时,请使用encodeURIComponent。

var p1 = encodeURIComponent("http://example.org/?a=12&b=55")

然后,我们可以创建所需的URL:

var url = "http://example.net/?param1=" + p1 + "&param2=99";

我们将获得以下完整的URL:

http://example.net/?param1 = http%3A%2F%2Fexample.org%2F%Ffa%3D12%26b%3D55&param2 = 99

请注意,encodeURIComponent不会转义""字符。一个常见的错误是使用它来创建html属性,例如href ='MyUrl',这可能会导致注入错误。如果要从字符串构造html,请在属性引号中使用""而不是"",或者添加额外的编码层("'可以被编码为%27")。

有关这种编码类型的更多信息,请查看:http://en.wikipedia.org/wiki/Percent-encoding