JS gets the parameter value (QueryString) in the URL in four ways to share

  • 2020-03-30 02:39:22
  • OfStack

Method 1: regular method

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:
alert(GetQueryString(" Parameter names 1"));
alert(GetQueryString(" Parameter names 2"));
alert(GetQueryString(" Parameter names 3"));


Method 2: split method

function GetRequest() {
    var url = location.search; //Get the "?" in the url String after a string
    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;
//Parameter 1 = Request[' parameter 1'];
//Parameter 2 = Request[' parameter 2'];
//Parameter 3 = Request[' parameter 3'];
//  parameter N = Request[' parameter N'];

Method 3: see regularization again

Get the url parameter through JS, which is used a lot. For example, a url:http://wwww.jb51.net/? Q =js, we want to get the value of the parameter q, which can be called through the following function.


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

Method 4: the method of obtaining a single parameter

The function GetRequest () {
    Var url = location. The search; // get "?" in the url String after a string
    If (url. IndexOf ("?" )! = 1) {      // to determine whether there are parameters
          Var STR = url. Substr (1); // start with the first character because the 0th character is? Gets all strings except the question mark
          STRS = STR. The split (" = ");     // is separated by an equal sign (because you know there is only one parameter, you should use the equal sign to separate if there are more than one parameter.)
          Alert (STRS [1]);                   // directly pop up the first parameter (if there are more than one parameter to loop)
    }
}

 


Related articles: