js 实现一个url格式化查询字符串函数

你可能会这么写,双重循环简单粗暴!

function parseQueryString(url) {
  let queryString = url.slice(url.indexOf('?')+1)
  let tempArr = queryString.split('&')
  let obj = {}
  tempArr.forEach(item => {
    let arr = item.split('=')
    obj[arr[0]] = arr[1]
  });
  return obj
}

let url ='https://www.google.com/search?sxsrf=ALeKk00CgwnIY5Zuno4bB9XsZirLV1KrZA%3A1594385155777&source=hp&ei=A2MIX7G-LKah-QbT87C4AQ&q=webpack&oq=webpack&gs_lcp=CgZwc3ktYWIQDFAAWABghBRoAHAAeACAAQCIAQCSAQCYAQCqAQdnd3Mtd2l6&sclient=psy-ab&ved=0ahUKEwjxy97G28LqAhWmUN4KHdM5DBcQ4dUDCAs'
console.log(parseQueryString(url))
// 打印结果
{
  sxsrf: 'ALeKk00CgwnIY5Zuno4bB9XsZirLV1KrZA%3A1594385155777',
  source: 'hp',
  ei: 'A2MIX7G-LKah-QbT87C4AQ',
  q: 'webpack',
  oq: 'webpack',
  gs_lcp: 'CgZwc3ktYWIQDFAAWABghBRoAHAAeACAAQCIAQCSAQCYAQCqAQdnd3Mtd2l6',
  sclient: 'psy-ab',
  ved: '0ahUKEwjxy97G28LqAhWmUN4KHdM5DBcQ4dUDCAs'
}

你可能感兴趣的:(JavaScript)