zoukankan      html  css  js  c++  java
  • 转载:escape,encodeURI,encodeURIComponent有什么区别?

    • escape
      unescape

    • encodeURI
      decodeURI

    • encodeURIComponent
      decodeURIComponent

    这六个方法功能有关联,如果不清楚每一个的作用,很容易混淆。问题的本质,是如何在 URL 中正确处理各种令人头疼的字符

    首先,escape unescape 已经废弃,应当避免使用。

    • The deprecated escape() method computes a new string in which certain characters have been replaced by a hexadecimal escape sequence. Use encodeURI or encodeURIComponent instead.

    • The deprecated unescape() method computes a new string in which hexadecimal escape sequences are replaced with the character that it represents. The escape sequences might be introduced by a function like escape. Because unescape is deprecated, use decodeURI or decodeURIComponent instead.

    根据 MDN 的说明,escape 应当换用为 encodeURI 或 encodeURIComponent;unescape 应当换用为 decodeURI 或 decodeURIComponent。


    那么,问题就简化为 encodeURI decodeURI 与encodeURIComponent decodeURIComponent 的区分。encodeURI 应当用于整个 URI 的编码,encodeURIComponent 应当用于 URI 中某个部分的编码。


    如果用 URL 举例,如下:

    encodeURI('https://www.baidu.com/ a b c')
    // "https://www.baidu.com/%20a%20b%20c"
    encodeURIComponent('https://www.baidu.com/ a b c')
    // "https%3A%2F%2Fwww.baidu.com%2F%20a%20b%20c"
    

    而 escape 会编码成下面这样,不伦不类,所以废弃。

    escape('https://www.baidu.com/ a b c')
    // "https%3A//www.baidu.com/%20a%20b%20c"
    

    由此可知,前端开发中用到最多的应该是 encodeURIComponent/decodeURIComponent。例如下面这个将 URL Search 中的参数转化为对象的方法:

    var parseUrlSearch = function() {
      var query = window.location.search.slice(1);
      var result = {};
      query.split("&").forEach(function(part) {
        var item = part.split("=");
        result[item[0]] = decodeURIComponent(item[1]);
      });
      return result;
    };


    作者:天方夜
    链接:https://www.zhihu.com/question/21861899/answer/62546831
    来源:知乎
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
  • 相关阅读:
    eclipse整合spring+springMVC+Mybatis
    复杂系统分析与设计思路
    .NET数据挖掘与机器学习开源框架
    原来rollup这么简单之 rollup.watch篇
    面试官:说说你对css效率的理解
    两个实用的调试技巧
    Roma
    一个很实用的css技巧简析
    仅仅知道如何终止XHR请求,或许对你来说是不够的!
    再问你一遍,你真的了解try..catch(finally)吗???
  • 原文地址:https://www.cnblogs.com/dongtianqi/p/7543213.html
Copyright © 2011-2022 走看看