经常会遇到这样的需求,将一个get类型的数据解析出来成一个json数据,如将http://item.taobao.com/item.htm?a=1&b=2&c=&d=xxx&e,解析成{a:’1′,b:’2′,c:”,d:'xxx',e:undefined}
var url = 'http://item.taobao.com/item.htm?a=1&b=2&c=&d=xxx&e[]=1&e[]=2&e[]=3'; function parseUrl(url){ var queryString = url.split('?')[1].split('&'); var json = {}; queryString.forEach(function(el,index){ var _temp = el.split('='); var index = _temp[0].indexOf('[]') if( index == -1 ){ json[_temp[0]] = _temp[1]; }else{ if(json[_temp[0].substr(0,index)]){ json[_temp[0].substr(0,index)].push(_temp[1]); }else{ json[_temp[0].substr(0,index)] = []; } } }); return json; } console.log(parseUrl(url));
运行结果: