使用execAll 实现getParam():直接拿到哈希值

169 阅读1分钟
var str = 'http://www.zhufengpeixun.cn/?lx=1&from=wx&b=12&c=13';
function getParam(url){
    var reg = /([^?=&]+)=([^?=&#])/g;//以=分割获取索要的字符
    let obj = {};
    reg.execAll(url).forEach(item =>{//execAll分割成:大正则内容 小分组1 小分组2:["lx=1", "lx", "1",
        obj[item[1]] = item[2];//不需要再分割,直接使用索引1和索引2获取就可以了
    })
    let v = url.match(/#(.+)/)?url.match(/#(.+)/)[1] : null;
    obj.hash = v;
    return obj
}
console.log(getParam(str));////{lx: "1", from: "wx", b: "12", c: "13"}
//第二种 使用replace方法实现getParam();
var str = 'http://www.zhufengpeixun.cn/?lx=1&from=wx&b=12&c=13';
 function getParam(url){
     var reg = /([^?=&]+)=([^?=&#]+)/g; //以=号分割,获取想要的字符
     let obj = {};
     var res = str.replace(reg,function($0,$1,$2){
         //$0代表大正则内容 $1代表第一个分组 $2代表第二个分组
         obj[$1] = $2;
     })
     let v = url.match(/#(.+)/) ? url.match(/#(.+)/)[1] : null;
            obj.hash = v;
            return obj;
 }
console.log(getParam(str));//{lx: "1", from: "wx", b: "12", c: "13"}
//第三种方法match 实现 getParam()
var str = 'http://www.zhufengpeixun.cn/?lx=1&from=wx&b=12&c=13';
function getParam(url){
    var reg =/([^?=&]+)=([^?=&#]+)/g
    var obj = {};
    url.match(reg).forEach(item =>{
        let a = item.split('=')//需要再以=切割一下变成:["lx", "1"]
        obj[a[0]] = a[1]
    })
    let v = url.match(/#(.+)/)?url.match(/#(.+)/)[1] : null;
    obj.hash =obj;
    return obj;
}
 console.log(getParam(str));//{lx: "1", from: "wx", b: "12", c: "13"}