zoukankan      html  css  js  c++  java
  • encodeURI()、encodeURIComponent()、escape()

    URI的通用格式如下:

    /***  协议://用户名:密码@子域名.域名.顶级域名:端口号/目录/文件名.文件后缀?参数1=值1&参数2=值2+值3#标志  **/
    /***  http://username:password@www.example.com:80/path/to/file.php?foo=316&bar=this+has+spaces#anchor **/

    URI由很多URI组件构成,协议、用户名、密码...等等。

    encodeURIComponent() 函数 与 encodeURI() 函数区别

    URI元字符(11个) :   /   @   ?  =   #  &  +   ;   $  ,

    encodeURIComponent() 函数会转义URI元字符。

    encodeURI() 函数不会转义URI元字符。

    const str = "http://username:password@www.example.com:80/path/to/file.php?foo=316&bar=this+has+spaces#anchor";
    encodeURI(str)
    // http://username:password@www.example.com:80/path/to/file.php?foo=316&bar=this+has+spaces#anchor
    encodeURIComponent(str)
    // http%3A%2F%2Fusername%3Apassword%40www.example.com%3A80%2Fpath%2Fto%2Ffile.php%3Ffoo%3D316%26bar%3Dthis%2Bhas%2Bspaces%23anchor

    encodeURIComponent() 函数 与 encodeURI() 函数相同点

    两者都不会对非转义字符进行编码。如果想要实现编码,需要手动实现。

    非转义字符:

    1. 字母 a-z A-z

    2. 数字 0-9

    3.其他9个非转义字符:  _   .   !   ~   *   '   (   )  

    对于非转义字符的转义如下:

    function fixedEncodeURIComponent (str) {
      return encodeURIComponent(str).replace(/[!'()*~_-]/g, function(c) {
        return '%' + c.charCodeAt(0).toString(16);
      });
    }

    escape()函数

    escape()函数已经从新的web标准中废除,请尽量不要使用!!

    尽量使用上面的两个方法。

  • 相关阅读:
    BZOJ 2157: 旅游 (2017.7.21 6:30-2017.7.21 15:38 今日第一题。。)
    洛谷 P1021 邮票面值设计
    洛谷 P2912 [USACO08OCT]牧场散步Pasture Walking
    COGS 2111. [NOIP2015普及]扫雷游戏
    洛谷 P3038 [USACO11DEC]牧草种植Grass Planting
    COGS 1439. [NOIP2013]货车运输
    COGS 908. 校园网
    codevs 1422 河城荷取
    codevs 1183 泥泞的道路
    洛谷 P3390 【模板】矩阵快速幂
  • 原文地址:https://www.cnblogs.com/lyraLee/p/10948470.html
Copyright © 2011-2022 走看看