js Two ways to get the parameter passed in the address bar of

  • 2021-07-18 06:39:12
  • OfStack

Type 1: String splitting method

window. location. href or location. href or window. location get everything in the address bar

decodeURI () can decode the data in the address bar to recover Chinese data

window. search Get the question mark in the address bar and the data after the question mark


// Gets the address bar ( URL ) Parameters passed  
function GetRequest(value) { 
  //url Examples: www.bicycle.com?id="123456"&Name="bicycle" ;  
  var url = decodeURI(location.search); //?id="123456"&Name="bicycle";
  var object = {};
  if(url.indexOf("?") != -1)//url There is a question mark in, which means there are parameters.  
  {  
   var str = url.substr(1); // Get ? The following string 
   var strs = str.split("&"); // Divide the resulting parameters into arrays [id="123456",Name="bicycle"];
   for(var i = 0; i < strs.length; i ++) 
    {  
                    object[strs[i].split("=")[0]]=strs[i].split("=")[1]
              }
    }
  return object[value]; 
} 

Type 2: Regular matching method

In fact, the principle of this method is similar to that of the previous one, which is extracted from URL, but the extraction method is different.


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

Related articles: