获取url参数的两种方法
// 假如 完整的url是 http://test.com/data?a=10&b=20&c=30
function query(name) {
// search: 'a=10&b=20&c=30'
const search = location.search.substr(1) // 类似array.slice(1) 从?后开始截取
// 每一个key前边,要么是开始,要么是&符号 (^|&)
// =号后边匹配的值不包括&符号 ([^&]*)
// 值后边还有&或者结尾(&|$)
// i 不区分大小写
const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`, 'i')
const res = search.match(reg)
console.log(res) // res是一个数组 ["a=20&", "", "20", "&", index: 0, input: "a=20&b=30&c=40", groups: undefined]
if (res === null) {
return null
}
return res[2]
}
console.log(query('a')) // 10
console.log('d') // null
// URLSearchParams
function query(name) {
const search = location.search
const p = new URLSearchParams(search)
return p.get(name)
}
console.log(query('b')) // 20
将url参数解析为对象
function queryToObj() {
const res = {}
// search: 'a=10&b=20&c=30'
const search = location.search.substr(1) // 去掉前面的'?'
// search.split('&') ['a=10','b=20','c=30']
search.split('&').forEach(paramStr => {
// paramStr.split('=') ['a','10'] ['b','20'] ['c','30']
const arr = paramStr.split('=')
const key = arr[0]
const value = arr[1]
res[key] = value
})
return res // {a:10,b:20,c:30}
}
function queryToObj() {
const res = {}
const pList = new URLSearchParams(location.search)
pList.forEach((val, key) => {
res[key] = val
})
return res // {a:10,b:20,c:30}
}
网友评论