escape, encodeURI 和 encodeURIComponent 的区别
Javascript 中有三个 URI 编码函数, 他们都是全局函数, 但功能稍有不同, 这里简单解释下他们之间的区别:
encodeURI 只将 URI 中的空格和非 AscII 字符进行编码, 编码后的 URI 能正常访问.
encodeURIComponent 除了将所有非 AscII 字符编码外, 还会将一些特殊字符进行编码 (如 ?, &, /, :, # 等), 编码后的 URI 不可访问.
一般要将字符串作为 get 参数传递或保存为 Cookie 的, 都需要使用 encodeURIComponent 编码.
escape 的功能与 encodeURIComponent 的功能一样, 只是个别字符的差异, 对使用没有影响.
但 escape 方法已经在 ECMAScript v3 标准中被删除了, 所以不推荐使用.
对应的解码函数为 unescape, decodeURI 和 decodeURIComponent.
附上测试脚本:
-
var url = 'http://labs.phpz.org/jstest/null.html?a=TEST1&b=hello world#';
-
var results = ['URI: ' + url];
-
// escape
-
results.push('escape: ' + escape(url));
-
// encodeURI
-
results.push('encodeURI: ' + encodeURI(url));
-
// encodeURIComponent
-
results.push('encodeURIComponent: ' + encodeURIComponent(url));
-
document.write(results.join('<br />'));
-
-
/*
-
URI: http://labs.phpz.org/jstest/null.html?a=TEST1&b=hello world#
-
escape: http%3A//labs.phpz.org/jstest/null.html%3Fa%3DTEST1%26b%3Dhello%20world%23
-
encodeURI: http://labs.phpz.org/jstest/null.html?a=TEST1&b=hello%20world#
-
encodeURIComponent: http%3A%2F%2Flabs.phpz.org%2Fjstest%2Fnull.html%3Fa%3DTEST1%26b%3Dhello%20world%23
-
*/