对于ASCII字符,这三个函数的作用都是将字符转换成百分比编码(Percent-encoding),区别是各自排除编码的字符不同:
escape() will not encode: @*/+ encodeURI() will not encode: ~!@#$&*()=:/,;?+\' encodeURIComponent() will not encode: ~!*()\'
请看测试页面:test_for_escape_and_encodeURIComponent.html
此外,escape其实是window对象的方法,encodeURIComponent和encodeURI是JS内置函数。请看MDC里的资料:window.escape 和 Global_Functions/encodeURIComponent.
对于非ASCII字符,escape和encodeURIComponent差异比较大:
escape(\'雕\') == \'%u96D5\' encodeURIComponent(\'雕\') == \'%E9%9B%95\'
%u96D5是非标准Pecent-encoding, 现在已经没有标准支持。然而也并非一无是处,比如:
alert(decodeURIComponent(\'%5Cu96D5\'));
除非你放在Firefox的地址栏上通过伪协议执行,否则得不到“雕”字。
对于这种反转码最简单的办法,是用unescape:
var a = decodeURIComponent(\'%5Cu96D5\'); alert(unescape(a.replace(/\\\\u/g, \'%u\')));
