用JS解决url地址中参数乱码的问题

var url = window.location.herf;//获取url地址
var obj = {};    //最后输出的对象
var reg = /?/;   //要匹配的正则表达式
if(url.match(reg)) {
    var chars = url.split('?')[1];//获取参数
    var char = chars.split('&'); //获取键值对
    for(var i=0;i<char.length;i++) {
        var index = char[i].indexOf('=');
        if(index>0) {//是否含有=
            var name = char[i].slice(0,index);
            var value = char[i].slice(index+1);
            obj[decodeURIComponent(name)] = decodeURIComponent(value);
//decodeURIComponent() 函数可对 encodeURIComponent() 函数编码的 URI 进行解码。
//示例

<script type="text/javascript">

var test1="http://www.w3school.com.cn/My first/"

document.write(encodeURIComponent(test1)+ "<br />")
document.write(decodeURIComponent(test1))

</script>
//输出
http%3A%2F%2Fwww.w3school.com.cn%2FMy%20first%2F
http://www.w3school.com.cn/My first/

} } } console.log(obj)
原文地址:https://www.cnblogs.com/sarah-wen/p/10742687.html