提取出url 里的参数并转成对象


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function getUrlParams(url){
 let reg = /([^?&=]+)=([^?&=]+)/g
 let obj = { }
 url.replace(reg, function(){
     obj[arguments[1]] = arguments[2]
})
 // 或者
 const search = window.location.search
 search.replace(/([^&=?]+)=([^&]+)/g, (m, $1, $2)=>{obj[$1] = decodeURIComponent($2)})
 
 return obj
}
let url = 'https://www.junjin.cn?a=1&b=2'
console.log(getUrlParams(url)) // { a: 1, b: 2 }