获取url地址?后面传递的参数
2020-06-07 本文已影响0人
小柠有点萌
let url="http://www.zidingyi.com/index.html?lx=2&name=sr&val=aaa";
拿到以下结果
/*
- {
- lx="2",
- name="sr",
- val="aaa"
- }
*/
第一种方式
// 1.获取问好后面的值
let askIndex=url.indexOf("?")
console.log(askIndex) //?的索引
let askText=url.substr(askIndex+1)
console.log(askText) //获取到值 lx=2&name=sr&val=aaa
//2 将lx=2&name=sr&val=aaa用数组拆分
let splitText = askText.split("&")
console.log(splitText) //=>["lx=2", "name=sr", "val=aaa"]
//3 将["lx=2", "name=sr", "val=aaa"]用:分隔
let result={}
splitText.forEach((item,index)=>{
let n = item.split("=")
let key =n[0];
let value =n[1];
result[key]=value;
});
console.log(result) //=> {lx: "2", name: "sr", val: "aaa"}
第二种方式基于正则封装
let url="http://www.zidingyi.com/index.html?lx=2&name=sr&val=aaa#rrr";
function queryURLParams(url) {
let result={}
reg1=/([^?=&#]+)=([^?=&#]+)/g,
reg2=/#([^?=&#]+)/g;
url.replace(reg1,(n,x,y)=>result[x]=y);
url.replace(reg2,(n,x)=>result['HASH']=x);
return result
}
let paramsObj=queryURLParams(url)
console.log(paramsObj) //=>{lx: "2", name: "sr", val: "aaa", HASH: "rrr"}