逃逸()
不要使用它! escape()
在B.2.1.2节Escape中定义,附件B的引言文本说:
...本附件中指定的所有语言功能和行为均具有一个或多个不良特征,在没有遗留用法的情况下,将从本规范中删除。 ...
在编写新的ECMAScript代码时,程序员不应使用或假定这些功能和行为的存在。
行为:
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
是不允许的。
encodeURI()
需要有效的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
encodeURIComponent()
当您想对URL参数的值进行编码时,请使用encodeURIComponent。
var p1 = encodeURIComponent("http://example.org/?a=12&b=55")
然后,您可以创建所需的URL:
var url = "http://example.net/?param1=" + p1 + "¶m2=99";
您将获得以下完整的URL:
http://example.net/?param1=http%3A%2F%2Fexample.org%2F%Ffa%3D12%26b%3D55¶m2=99
请注意,encodeURIComponent不会转义'
字符。 一个常见的错误是使用它来创建html属性,例如href='MyUrl'
,这可能会遇到注入错误。 如果要从字符串构造html,请在属性引号中使用"
代替'
,或添加额外的编码层( '
可以编码为%27”)。
有关此类型编码的更多信息,请检查: http : //en.wikipedia.org/wiki/Percent-encoding