let url = 'http://www.douqu.com/index.html?name1=val1&name2=val2'; //1.提取问号后的字符 let asktext = url.substring(url.indexOf('?')+1,url.length); //2.后面值的处理 let askary = asktext.split('&'); askary.forEach((item)=>{ let n = item.split('='); let key = n[0]; let value = n[1]; result[key] = value; }); console.log(result);
优化方案,进行函数封装,考虑多种情况
//考虑有无哈希值与问号的存在 /* @params:url[string] @return:[object]包含参数和哈希信息的对象 */ function queryURLParams(url){ let askIn = url.indexOf('?'); let wellIn = url.indexOf('#'); let welltext = ''; let asktext = ''; //#不存在,?存在时所做的事,并获取将要处理的字符片段 wellIn === -1?wellIn=url.length : wellIn; askIn >= 0?asktext = url.substring(askIn+1,wellIn) : null; welltext = url.substring(wellIn+1); //处理信息 let result = {}; welltext!=='''?result['hash'] = well : null; if(asktext!==""){ let ary = asktext.split('&'); ary.forEach((item=>{ let n = item.split('='); let key = n[0]; let value = n[1]; result[key] = value; })); } return result; }
正则方式实现
function queryURLParams(){ let result = {}; reg1 = /([^?=&#]+)=([^?=&#]+)/g reg2 = /#([^?=&#]+)/g url.replace(reg1,(n,x,y)=>result[x]=y); url.replace(reg2,(n,x)=>result['hash']=x); return result; } //正则的强大由此可见