且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-25 14:56:37

escape()



不要使用它,因为自ECMAScript v3起已被弃用。



encodeURI()



当您想要一个工作的URL时,请使用encodeURI。拨打此电话:

  encodeURI(http://www.google.com/a file with spaces.html)

获取:

 code> http://www.google.com/a%20file%20with%20spaces.html 

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

  http%3A%2F%2Fwww.google。 com%2Fa%20file%20with%20spaces.html 



encodeURIComponent()



当您要对URL参数进行编码时,请使用encodeURIComponent。

  param1 = encodeURIComponent(http: //example.com/?a=12&b=55)

然后你可以创建您需要的网址:

  url =http://domain.com/?param1=+ param1 +& param2 = 99\" ; 

你会得到这个完整的URL:



http://www.domain.com/?param1=http%3A%2F%2Fxyz.com%2F%Ffa%3D12%26b%3D55&param2=99



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



有关此类型编码的更多信息,您可以检查: http://en.wikipedia.org/wiki/Percent-encoding


When encoding a query string to be sent to a web server - when do you use escape() and when do you use encodeURI() or encodeURIComponent():

Use escape:

escape("% +&=");

OR

use encodeURI() / encodeURIComponent()

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

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

escape()

Don't use it, as it has been deprecated since ECMAScript v3.

encodeURI()

Use encodeURI when you want a working URL. Make this call:

encodeURI("http://www.google.com/a file with spaces.html")

to get:

http://www.google.com/a%20file%20with%20spaces.html

Don't call encodeURIComponent since it would destroy the URL and return

http%3A%2F%2Fwww.google.com%2Fa%20file%20with%20spaces.html

encodeURIComponent()

Use encodeURIComponent when you want to encode a URL parameter.

param1 = encodeURIComponent("http://example.com/?a=12&b=55")

Then you may create the URL you need:

url = "http://domain.com/?param1=" + param1 + "&param2=99";

And you will get this complete URL:

http://www.domain.com/?param1=http%3A%2F%2Fxyz.com%2F%Ffa%3D12%26b%3D55&param2=99

Note that encodeURIComponent does not escape the ' character. A common bug is to use it to create html attributes such as href='MyUrl', which could suffer an injection bug. If you are constructing html from strings, either use " instead of ' for attribute quotes, or add an extra layer of encoding (' can be encoded as %27).

For more information on this type of encoding you can check: http://en.wikipedia.org/wiki/Percent-encoding