编写一个解析url中参数的函数
代码
const searchKey = window.location.href.indexOf("?")
const searchUrl = searchKey > 0 ? window.location.href.slice(searchKey + 1) : ""
function queryParam(str) {
const result = {}
if (str.length > 0) {
str.split("&").forEach(element => {
const temp = element.split("=")
result[temp[0]] = temp[1]
})
}
return result
}
console.log(queryParam(searchUrl))
end
- 无非就是截取url中的问号后的字符串,基于
&
切割成数组。 - 遍历该数组,再基于
=
切割即可。