Seven Yu @ 12/10/2009 (12:38 pm)

escape, encodeURI 和 encodeURIComponent 的区别

Javascript 中有三个 URI 编码函数, 他们都是全局函数, 但功能稍有不同, 这里简单解释下他们之间的区别:

encodeURI 只将 URI 中的空格和非 AscII 字符进行编码, 编码后的 URI 能正常访问.
encodeURIComponent 除了将所有非 AscII 字符编码外, 还会将一些特殊字符进行编码 (如 ?, &, /, :, # 等), 编码后的 URI 不可访问.
一般要将字符串作为 get 参数传递或保存为 Cookie 的, 都需要使用 encodeURIComponent 编码.

escape 的功能与 encodeURIComponent 的功能一样, 只是个别字符的差异, 对使用没有影响.
但 escape 方法已经在 ECMAScript v3 标准中被删除了, 所以不推荐使用.

对应的解码函数为 unescape, decodeURI 和 decodeURIComponent.

附上测试脚本:

PLAIN TEXT >> JAVASCRIPT:
  1. var url = 'http://labs.phpz.org/jstest/null.html?a=TEST1&b=hello world#'
  2. var results = ['URI: ' + url]
  3. // escape
  4. results.push('escape: ' + escape(url));
  5. // encodeURI
  6. results.push('encodeURI: ' + encodeURI(url));
  7. // encodeURIComponent
  8. results.push('encodeURIComponent: ' + encodeURIComponent(url))
  9. document.write(results.join('<br />'));
  10.  
  11. /*
  12. URI: http://labs.phpz.org/jstest/null.html?a=TEST1&b=hello world#
  13. escape: http%3A//labs.phpz.org/jstest/null.html%3Fa%3DTEST1%26b%3Dhello%20world%23
  14. encodeURI: http://labs.phpz.org/jstest/null.html?a=TEST1&b=hello%20world#
  15. encodeURIComponent: http%3A%2F%2Flabs.phpz.org%2Fjstest%2Fnull.html%3Fa%3DTEST1%26b%3Dhello%20world%23
  16. */

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>