js获取url中的中文参数出现乱码

440 阅读1分钟

问题场景

获取url传递参数,参数值带有中文,如url?name=张三,js获取后出现乱码。

问题分析

浏览器对url自动进行编码,获取中文需进行解码,采用decodeURIComponent。

问题解决

获取特定参数工具函数

function getQueryString(key){
        var reg = new RegExp("(^|&)"+key+"=([^&]*)(&|$)");
        var result = window.location.search.substr(1).match(reg);
        return result?decodeURIComponent(result[2]):null;
      }