1. URLSearchParams() 方法
- URLSearchParams() 构造器创建并返回一个新的URLSearchParams 对象。 开头的'?' 字符会被忽略。
- new URLSearchParams(参数1)
- 参数1:传的url是"?"后的东西 如 ?id=165481651635&dsf=sd&p=658
- 可通过window.location.search获取
const urlSearchParams = new URLSearchParams(window.location.search);
const params = Object.fromEntries(urlSearchParams.entries());
console.log(params);
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.baidu.com?user=%E9%98%BF%E9%A3%9E&age=16')
console.log(user)