Javascript中escape/encodeURI/encodeURIComponent有何区别
escape()
已在 ECMAScript v3 中废弃。
encodeURI()
如果你需要编码一个URL(如:放进href属性中),就调用这个函数:
encodeURI("http://www.google.com/a file with spaces.html")
获得结果:
http://www.google.com/a%20file%20with%20spaces.html
不要使用encodeURIComponent,否则你会得到如下结果:
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 + "¶m2=99";
获得如下结果
http://www.domain.com/?param1=http%3A%2F%2Fxyz.com%2F%Ffa%3D12%26b%3D55¶m2=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).