JavaScript:html获取url参数

使用場景:常用在分享页面 

1、采用正则表达式获取地址栏参数 

function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i" );
    var r = window.location.search.substr(1).match(reg);
    if (r != null){
        return unescape(r[2]);
    }else{
        return null ;
    }
}

2、split拆分法 

function getQueryString() {
    // 获取url中"?"符后的字串
    const url = location.search; 
    let theRequest = new Object();
    if (url.indexOf("?") != -1) {
       let str = url.substr(1);
       strs = str.split("&");
       for(let i = 0; i < strs.length; i ++) {
          theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);
       }
    }
    return theRequest;
}

你可能感兴趣的:(JavaScript,javascript,html)