获取url参数并转换成对象

2021-05-16  本文已影响0人  RickyWu585

示例url:localhost:8080?name=mike&age=20

window.location.search
// ?name=mike&age=20
function getQueryParams(){
  const result = {}
  const querystring =  window.location.search
  // ?name=mike&age=20
  const reg = /[?&][^?&]+=[^?&]+/g
  const found = querystring.match(reg)
   // ['?name=mike',&age=20]
  if(found){
    found.foreach(item = > {
        let temp = item.substring(1).split('=')
        let key = temp[0]
        let value = temp[1]
        result[key] = value
    })
  }  
  return result
}
上一篇下一篇

猜你喜欢

热点阅读