js 对中文字符的 解码 与 编码_js中文编码-CSDN博客

js 对中文字符的 解码 与 编码

1、 decodeURIComponentencodeURIComponent

1.1、decodeURIComponent 解码字符
  • 功能: 解码由 encodeURIComponent 方法或者其它类似方法编码的标识符,一般用于解码标识符为中文

  • Demo:

    let encodeStr = encodeURIComponent('中文')
    console.log(encodeStr)   //  "%E4%B8%AD%E6%96%87"
    
    let decodeStr = decodeURIComponent(encodeStr)
    console.log(decodeStr)     //  "中文"
    
1.2、encodeURIComponent 编码字符
  • 功能: 把字符串作为 URI 组件进行编码
  • Demo:
var uri="李先生&car=abc";
document.write(encodeURIComponent(uri));   //%E6%9D%8E%E5%85%88%E7%94%9F%26car%3Dabc

2、decodeURIencodeURI

2.1、encodeURI 函数可把字符串作为 URI 进行编码。
  • 注意: 对以下在 URI 中具有特殊含义的 ASCII 标点符号,encodeURI() 函数是不会进行转义的: , / ? : @ & = + $ #(可以使用 encodeURIComponent() 方法分别对特殊含义的 ASCII 标点符号进行编码。)。空格转化为%20

  • Demo:

    var uri="my test.php?name=陈先生&car=saab";
    console.log(encodeURI(uri));      // my%20test.php?name=%E9%99%88%E5%85%88%E7%94%9F&car=saab
    
2.2、decodeURI 函数可对 encodeURI() 函数编码过的 URI 进行解码。
  • 功能: 可对 encodeURI() 函数编码过的 URI 进行解码
  • Demo:
  var uri="my test.php?name=陈先生&car=saab";
  var encodeUri = encodeURI(uri);
  var decodeUri = decodeURI(encodeUri );
  console.log( decodeUri );   //  my test.php?name=陈先生&car=saab

3、decodeURI与decodeURIComponent区别

  • encodeURI()主要用于整个URI(例如,http://www.jxbh.cn/illegal value.htm),
    encode-URIComponent()主要用于对URI中的某一段(例如前面URI中的illegal value.htm)进行编码

  • encodeURI()不会对本身属于URI的特殊字符进行编码,例如冒号、正斜杠、问号、等号和井号
    encodeURIComponent()则会对它发现的任何非标准字符进行编码

    var uri="http://www.jxbh.cn/illegal?name=李 ";
    console.log(encodeURI(uri));    // 不对 冒号、正斜杠、问号、等号和井号 编码
    //http://www.jxbh.cn/illegal?name=%E6%9D%8E%20
    
    console.log( encodeURIComponent(uri));   // 对 冒号、正斜杠、问号、等号和井号 编码
    //http%3A%2F%2Fwww.jxbh.cn%2Fillegal%3Fname%3D%E6%9D%8E%20
    

在实践中更常见的是对查询字符串参数而不是对基础URL进行编码,因此decodeURIComponent用的比decodeURI要多。

参考链接:https://www.cnblogs.com/hamsterPP/p/7131163.html

  • 8
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值