zoukankan      html  css  js  c++  java
  • decodeURI和 decodeURIComponent以及encodeURI和encodeURIComponent的区别

    url传递参数这是很常见数据传递方式,但如果不注意也是很容易出现问题的。

    最常见的就是url传递中文乱码了以及空格被转码,而要避免这种问题出现的最佳解决方案是传递前编码,接收数据后解码。编码我们用encodeURIencodeURIComponent,解码我们用decodeURIdecodeURIComponent

    encodeURI() 把字符串编码为 URI。(对应decodeURI)
    encodeURIComponent() 把字符串编码为 URI 组件。
    decodeURI() 解码某个编码的 URI。对应encodeURI)
    decodeURIComponent() 解码一个编码的 URI 组件。(对应encodeURIComponent)

    这两种转码和解码方式具体有什么区别呢?看下面几行代码运行结果就知道了:

    var urlStr="http://www.coolfish.cn/tag/url中文乱码";  
    var enURI=encodeURI(urlStr);  
    var deURI=decodeURI(urlStr);   
    var enURIC=encodeURIComponent(urlStr);  
    var deURIC=decodeURIComponent(urlStr);
    console.log("初始URL:"+urlStr);
    console.log("encodeURI转码:"+enURI);
    console.log("decodeURI解码:"+deURI);
    console.log("encodeURIComponent转码:"+enURIC);
    console.log("decodeURIComponent解码:"+deURIC);
    

      运行结果:

    初始URL:http://www.coolfish.cn/tag/url中文乱码
    encodeURI转码:http://www.coolfish.cn/tag/url%E4%B8%AD%E6%96%87%E4%B9%B1%E7%A0%81
    decodeURI解码:http://www.coolfish.cn/tag/url中文乱码
    encodeURIComponent转码:http%3A%2F%2Fwww.coolfish.cn%2Ftag%2Furl%E4%B8%AD%E6%96%87%E4%B9%B1%E7%A0%81
    decodeURIComponent解码:http://www.coolfish.cn/tag/url中文乱码

    可以看到encodeURIComponent转码的时候会把uri进行编码(url中的://转码了)。

    当我们的url传递类似callbackURL的参数的时候,最好是使用encodeURIComponent和decodeURIComponent来编码和转码。

  • 相关阅读:
    Go 好用第三方库
    Go 的beego 框架
    Go 的gin 框架 和 gorm 和 html/template库
    Go 常用的方法
    Dijkstra 的两种算法
    邻接矩阵
    next permutation 的实现
    最优二叉树 (哈夫曼树) 的构建及编码
    思维题— Count the Sheep
    STL— bitset
  • 原文地址:https://www.cnblogs.com/fixbug/p/4004400.html
Copyright © 2011-2022 走看看