封装方法
function getObjParam(url) {
let obj = {};
const arr = url.split("?")[1].split("&");
arr.forEach(v => obj[v.split("=")[0]] = v.split("=")[1]);
return obj;
}
使用方法
const url = 'http://www.xxx.com/index?id=77&=2905210001&page=1';
console.log(getObjParam(url)); // { id: "77", userId: "2905210001", page: "1" }
完整代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS截取地址?后的值变成对象</title>
</head>
<body>
<script>
const url = 'http://www.xxx.com/index?id=77&=2905210001&page=1';
function getObjParam(url) {
let obj = {};
const arr = url.split("?")[1].split("&");
arr.forEach(v => obj[v.split("=")[0]] = v.split("=")[1]);
return obj;
}
console.log(getObjParam(url)); // { id: "77", userId: "2905210001", page: "1" }
</script>
</body>
</html>