zoukankan      html  css  js  c++  java
  • 前端js编码

    1、首先是encodeURI和encodeURIComponent;

    从名字可以清晰的看出他两都是主要用于url编码的,那之间有什么区别呢?唯一区别就是编码的字符范围,其中

    encodeURI方法不会对下列字符编码  ASCII字母、数字、~!@#$&*()=:/,;?+';

    encodeURIComponent方法不会对下列字符编码 ASCII字母、数字、~!*()';

    很明显encodeURIComponent要比encodeURI编码更多东西,也就是更加严格

        var url="https://www.baidu.com?name=123sex=man";
        var test2=encodeURI(url);
        var test=encodeURIComponent(url);
        console.log(test2)
        console.log(test)

    上面简单的例子也很明显。他两相对应的解码为decodeURI()、decodeURIComponent()

    2、btoa与atob

    WindowOrWorkerGlobalScope.btoa()  从 String 对象中创建一个 base-64 编码的 ASCII 字符串,其中字符串中的每个字符都被视为一个二进制数据字节。简单来说就是base64编码。

        var url="https://www.baidu.com";
        var test2=window.btoa(url);
        console.log(test2)        //aHR0cHM6Ly93d3cuYmFpZHUuY29t

    从上面的例子可以看出已经被编码成base64格式,但当我们采用中文时会发现报错,

        var url="深圳南山";
        var test2=window.btoa(url);
        console.log(test2)

    我们运行后会发现报错如下图

    这是为什么呢?由于这个函数将每个字符视为二进制数据的字节,而不管实际组成字符的字节数是多少,所以如果任何字符的码位超出 0x00 ~ 0xFF 范围,则会引发 InvalidCharacterError 异常。请参阅 Unicode_字符串 ,该示例演示如何编码字符数超出 0x00 ~ 0xFF 范围的字符串,我们通过以下方式完成编码

        var url="深圳南山";
        function utf8_to_b64( str ) {
            return window.btoa(unescape(encodeURIComponent( str )));
        }
        function b64_to_utf8( str ) {
            return decodeURIComponent(escape(window.atob( str )));
        }
        console.log(utf8_to_b64(url))  //5rex5Zyz5Y2X5bGx
      
      console.log(b64_to_utf8(utf8_to_b64(url)))  //深圳南山
    在js引擎内部,encodeURIComponent(str)相当于escape(unicodeToUTF8(str))所以可以推导出unicodeToUTF8(str)等同于unescape(encodeURIComponent(str))

     3、escape() 

    escape() 函数可对字符串进行编码,该方法不会对 ASCII 字母和数字进行编码,也不会对下面这些 ASCII 标点符号进行编码: * @ - _ + . / 。其他所有的字符都会被转义序列替换。

        var url="深圳南山/&@3232";
        var test=escape(url)
        console.log(test)  //%u6DF1%u5733%u5357%u5C71/%26@3232

    unescape() 函数可对通过 escape() 编码的字符串进行解码。不过ECMAScript v3 已从标准中删除了 unescape() 函数,并反对使用它,因此应该用 decodeURI() 和 decodeURIComponent() 取而代之。

  • 相关阅读:
    学习canvas过程中的小菜鸟
    小菜鸟谈html语义化
    mui常用方法
    mui的侧滑菜单如何禁用手势侧滑
    ajax 传递数组参数
    LNMP状态管理命令
    LNMP相关软件目录及文件位置
    ubuntu常用命令
    Ubuntu设置允许root用户登录
    linux一键安装web环境(sh-1.3.0)
  • 原文地址:https://www.cnblogs.com/yuanzhiguo/p/9431466.html
Copyright © 2011-2022 走看看