Getting parameter values from a URL is a common requirement in the development process of Che program, and by accident cannot, it is time to study the method of obtaining parameters under Javasrcipt (similar in Java).
First look at the URL specification:
URL consists of:
Protocol://hostname[:p ORT]/path/[;p Arameters][?query] #fragment
Protocol://hostname [: Port]/path/[: parameter] [? query] #Fragment
A canonical URL parameter is always in the "? Query "section, with" Variable name = value "In the form of such existence;
This gives us an idea of how to value:
The first method: use regular expressions to get the values of the corresponding parameters we need from the URL
1 functionGeturlprambyname (name) {2 varurl = window.location.search;//get the URL? After the content3 varReg =NewRegExp ("(^|&)" + name + "= ([^&]*) (&|$)", "I"); 4 if(URL) {5 varr = Url.substr (1). Match (REG); 6 7 if(r! =NULL) {8 returndecodeURI (r[2]); 9}Else{Ten return NULL; One } A }; -};
You can do it yourself in the browser console, this method can only be used alone, to get the parameters that you need to be worth the variable
The second approach: use string manipulation to put all the required values
functionGetallurlpram () {varurl = window.location.search;//get what's behind the URL? if(URL && url.indexof ("?")! =-1) {URL= Url.substr (1);//Remove the front? vararr = Url.split ("&");//Converts a string to an array with a & delimiter varobj = {};//define an empty object for(vari=0;i<arr.length;i++){ varSTR0 = Arr[i].split ("=") [0],//converts each element string in the array to an array separated by "=", the first element of the array is the keySTR1 = Arr[i].split ("=") [1];//converts each element string in the array to an array that is split with "=", the first element of the array is the valueOBJ[STR0] = decodeURI (STR1);//You must use decodeURI for decoding because the escaped character is used in the URL } returnobj; }Else { return NULL; }}
So we can define a generic method on the string prototype chain:
String.prototype.getUrlParms =function(){ varindex = This. IndexOf ("?"); if(Index!=-1){ varstr = This. substr (index+1); vararr = Str.split ("&");//Converts a string to an array with a & delimiter varobj = {};//define an empty object for(vari=0;i<arr.length;i++){ varSTR0 = Arr[i].split ("=") [0],//converts each element string in the array to an array separated by "=", the first element of the array is the keySTR1 = Arr[i].split ("=") [1];//converts each element string in the array to an array that is split with "=", the first element of the array is the valueOBJ[STR0] = decodeURI (STR1);//You must use decodeURI for decoding because the escaped character is used in the URL } returnobj; }Else{ return; }}
final execution of the string geturlparms () method, you get a worthy object that contains all the required parameters and parameters;
Javasrcipt the way to get arguments from a URL or from a string