如何获取URL参数

1、使用URLSearchParams 方法

// 创建URLSearchParams实例
const urlSearchParams = new URLSearchParams(window.location.search)
// Object.fromEntries() 方法把键值对列表转换为一个对象
// URLSearchParams.entries() 返回一个iterator可以遍历所有键/值对的对象
const params = Object.fromEntries(urlSearchParams.entries())

2、使用split 方法

function getParams(url) {
  const res = {}
  if (url.includes('?')) {
    const str = url.split('?')[1]
    const arr = str.split('&')
    arr.forEach(item => {
      const key = item.split('=')[0]
      const val = item.split('=')[1]
      res[key] = decodeURIComponent(val) // 解码
    })
  }
  return res
}


const user = getParams('http://www.bilibili.com?user=vivian&age=18')
console.log(user) // { user: 'vivian', age: '18' }

猜你喜欢

转载自blog.csdn.net/qq_61006976/article/details/122703941
今日推荐