Skip to content

将URL中的查询字符串转为对象

js
const url = 'https://juejin.cn/search?query=132312&fromSeo=0&fromHistory=0&enterFrom=detail_page&type=0'

方法一

使用Api

js
// 返回回个 URLSearchParm 对象
// 官方文档地址: https://developer.mozilla.org/zh-CN/docs/Web/API/URLSearchParams
new URLSearchParm(url)

方法二

自己实现

ts
function queryToObj(url: string): Object {
  const obj: Object = { a: 1}
  const queryStr = url.slice(url.indexOf('?') + 1, url.length)
  const queryList = queryStr.split('&')
  queryList.forEach(i => {
    const [ key, value ] = i.split('=')
    const decodeKey = decodeURIComponent(key)
    const decodeValue = decodeURIComponent(value)
    if (obj.hasOwnProperty(decodeKey)) {
      if (Array.isArray(obj[decodeKey])) {
        obj[decodeKey].push(decodeValue)
      } else {
        obj[decodeKey] = [ obj[decodeKey], decodeValue ]
      }
    } else {
      obj[key] = value
    }
  })

  return obj
}