给定一段 URL 地址截取后面的 GET 参数转成对象(key-value形式)

360 阅读1分钟

给定一段 URL 地址截取后面的 GET 参数转成对象

有这样一个 URL: http://xxxxrerr.htm?a=1&b=2&c=&d=xxx&e, 请写一段 JS 程序提取 URL 中的各个 GET 参数(参数名和参数个数不确定),将其按 key-value形式返回到一个 json 结构中,如 {a: "1", b: "2", c: "", d: "xxx", e: undefined}

// 给定一段 url 地址
let str = 'http://xxxxrerr.htm?a=1&b=2&c=&d=xxx&e'

// 先把字符 ? 后面的字符截取出来
let newStr = str.substr(str.indexOf('?') + 1)

// 通过 reduce 方法进行处理
let newObj = newStr.split('&').reduce((obj, item) => {
  let itemArr = item.split('=') // ['a', '1']
  obj[itemArr[0]] = itemArr[1] // {a: 1}
  return obj
}, {})

console.log(newObj) // {a: '1', b: '2', c: '', d: 'xxx', e: undefined}

还有一种更加帅气的写法

// 给定一段 url 地址
let str = 'http://xxxxrerr.htm?a=1&b=2&c=&d=xxx&e'

// 先把字符 ? 后面的字符截取出来
let newStr = str.substr(str.indexOf('?') + 1)

// 通过 reduce 方法进行处理
let newObj = newStr.split('&').reduce((obj, item) => ((obj[item.split('=')[0]] = item.split('=')[1]), obj), {})

console.log(newObj) // {a: '1', b: '2', c: '', d: 'xxx', e: undefined}