js获取当前url地址中的参数

第一种:只适用于/User/vip_card_manager?useless=219&id=18这种地址

function getUrlParam(name){
    var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if(r!=null)
        return decodeURI(r[2]);
    return null;
}
console.log(getUrlParam("id"));//结果:18

第二种:这两种地址都适用
/User/vip_card_manager/useless/219/id/18
/User/vip_card_manager?useless=219&id=18

function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var reg_rewrite = new RegExp("(^|/)" + name + "/([^/]*)(/|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    var q = window.location.pathname.substr(1).match(reg_rewrite);
    if(r != null){
        return decodeURI(r[2]);
    }else if(q != null){
        return decodeURI(q[2]);
    }else{
        return null;
    }
}
console.log(getUrlParam("id"));//结果:18
志博

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: