获取 url ?后面的参数,并将参数对象化

一,

    function parseQueryString(url) {
            var params = {};
            var arr = url.split("?");
            var arr1 = arr[1].split("&");
            // console.log('arr1',arr1)
            for (var i = 0; i < arr1.length; i++) {
                arr2 = arr1[i].split('='); 
                // console.log('arr2',arr2)
                if (!arr2[1]) { 
                    params[arr2[0]] = 'true';
                } else  if (params[arr2[0]]) { 
                    var arr3 = [params[arr2[0]]]; 
                    arr3.push(arr2[1]); params[arr2[0]] = arr3; 
                } else { 
                    params[arr2[0]] = decodeURI(arr2[1]);
                } 
            }
            console.log(params);  
        } 
        var url = 'http://www.baidu.com/?user=huixin&id=123&id=456&city=%E5%8C%97%E4%BA%AC&enabled'; 
        parseQueryString(url); 

二,

    var url = "http:www.xxx.net/x/x.html?id=898602B8261890349226&aa=123&bb=456&cc=789"
    var params = url.split("?")[1].split("&")
    var obj = {}
    //   for (i = 0; i < params.length; i++) {
    //   var param = params[i].split("=");
    //   obj[param[0]] = param[1]
    //   }
    params.map(v => obj[v.split("=")[0]] = v.split("=")[1])
    console.log(obj)

    const getURLParameters = url =>
        (url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(
            (a, v) => ((a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a),
            {}
        );
    var url = 'http://www.baidu.com/?user=huixin&id=123';
    console.log(getURLParameters(url))

你可能感兴趣的:(获取 url ?后面的参数,并将参数对象化)