1 split + map
function parse(url){ let obj={} url.slice(url.indexOf('? ')+1) .split('&') .map(i=>{ let [k,v]=i.split('=') obj[k]=v }) return obj } let url = "http://www.xxx.com?a=1&b=2&c=3" let result = parse(url); console.log(result); // { a: '1', b: '2', c: '3' }Copy the code
2 split + reduce
function parse(url){ return url.slice(url.indexOf('? ')+1) .split('&') .reduce((acc,cur)=>{ let[k,v]=cur.split('=') acc[k]=v return acc },{}) } let url = "http://www.xxx.com?a=1&b=2&c=3" let result = parse(url); console.log(result); // { a: '1', b: '2', c: '3' }Copy the code