js获取URL上的?值

获取URL上的值

推荐方案:正则表达式判断获取

function getUrlValue(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg); //获取url中"?"符后的字符串并正则匹配
    var context = "";
    if (r != null)
        context = decodeURIComponent(r[2]);
    reg = null;
    r = null;
    return context == null || context == "" || context == "undefined" ? "" : context;
}
如:
http://localhost:8080/abc.html?name=张三&age=18
let name = getUrlValue("name");  //name = 张三
let age = getUrlValue("age");  //age = 18

 

已有 0 条评论

    欢迎您,新朋友,感谢参与互动!