function urlParse(url) {
let decodeUrl = decodeURIComponent(url) // decodeURIComponent 用于对url进行解码操作
if (!decodeUrl || typeof decodeUrl !== 'string') {
throw new Error('请检查函数传参url类型是否正确')
}
if (!/http(s)?:\/\/[\w.]+[\w/]*\??[\w]*[\w&?=]*/g.test(decodeUrl)) {
throw new Error('输入url不合法')
}
let result = {}
let reg = /[^?&]+=[^?&]+/g //将不是?或者&的字符过滤并匹配整段文字中不是?或&的字符,同时参数的key与value是通过=来分割的,所以还需匹配等号后面的字符串
let match = decodeUrl.match(reg)
if (!match || match.length === 0) {
return decodeUrl
}
match.forEach(v => {
let temp = v.split('=')
let key = temp[0]
let value = temp[1]
result[key] = value
})
return result
}
JS 解析URL参数并以对象形式返回
最新推荐文章于 2023-10-19 21:06:36 发布