小编典典

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

javascript

编码要发送到 Web 服务器的查询字符串时 - 您何时使用escape()以及何时使用encodeURI()or encodeURIComponent()

使用转义:

escape("% +&=");

要么

使用 encodeURI() / encodeURIComponent()

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

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

阅读 237

收藏
2022-02-23

共1个答案

小编典典

不要使用它! 在B.2.1.2escape()节中定义了转义,附件 B的介绍文本说:

… 本附件中规定的所有语言特征和行为都有一个或多个不受欢迎的特征,在没有遗留使用的情况下,将从本规范中删除。…
… 程序员在编写新的 ECMAScript 代码时不应使用或假设存在这些特性和行为......

行为:

https://developer.mozilla.org/en-US/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是不允许的。

编码URI()

如果您想要一个工作 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 一样,encodeURI 不会转义 ‘ 字符。

编码URIComponent()

如果要对 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,请使用"而不是'for 属性引号,或者添加额外的编码层('可以编码为 %27)。

2022-02-23