JS gets the parameter value in the URL

//Method 1: regular law

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]);
    }
    return null;
}
// call like this:
alert(GetQueryString("Parameter name 1"));
alert(GetQueryString("Parameter name 2"));
alert(GetQueryString("Parameter name 3"));
//Method 2: split split method

function GetRequest() {
    var url = location.search; //Get the string after the "?" character in the url
    var theRequest = new Object();
    if (url.indexOf("?") != -1) {
        var str = url.substr(1);
        strs = str.split("&");
        for (var i = 0; i < strs.length; i++) {
            theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
        }
    }
    return theRequest;
}
var Request = new Object();
Request = GetRequest();
// var parameter 1, parameter 2, parameter 3, parameter N;
// parameter1 = Request['parameter1'];
// parameter 2 = Request['parameter 2'];
// parameter 3 = Request['parameter 3'];
// parameterN = Request['parameterN'];


//Method three: see also regular
//Get url parameters through JS, this is often used. For example, a url: http://www.jb51.net/?q=js, we want to get the value of the parameter q, then we can call it through the following function.

function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg); //Get the string after the "?" character in the url and match it regularly
    var context = "";
    if (r != null)
        context = r[2];
    reg = null;
    r = null;
    return context == null || context == "" || context == "undefined" ? "" : context;
}
alert(GetQueryString("q"));


//Method 4: How to get a single parameter
function GetRequest() {
    var url = location.search; //Get the string after the "?" character in the url
    if (url.indexOf("?") != -1) { //Determine whether there are parameters
        var str = url.substr(1); //Start from the first character because the 0th is a ? sign to get all strings except the question mark
        strs = str.split("="); //Separate with an equals sign (because you know there is only one parameter, so use an equals sign to separate directly. If there are multiple parameters, separate them with an & sign and then separate them with an equals sign)
        alert(strs[1]); //Pop up the first parameter directly (if there are multiple parameters, it will be looped)
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325859569&siteId=291194637