How can we get the url address bar link parameters? We can use the following methods, but I must use window. location. href to get the url address and then use the regular expression to match it.
Suppose the page address is like this. /P/165, then I want to get the last number 165, you can use this code
The Code is as follows: |
Copy code |
Var url = window. location. href; Var index = url. substring (url. lastIndexOf ('/') + 1 ); |
However, this is flawed. If the obtained address is not in this form, but/tools, then the index value is not a number.
Solution
Which of the following may be better?
The Code is as follows: |
Copy code |
Var lastBit = url. substring (url. lastIndexOf ('/') + 1). match (/[^/] * $/) [0]; Var lastDigits = url. substring (url. lastIndexOf ('/') + 1). match (/[0-9] * $/) [0]; |
// Obtain the query value from the numeric part.
The Code is as follows: |
Copy code |
<Script type = "text/javascript"> (Function ($ ){ $. GetUrlParam = function (name) { Var reg = new RegExp ("(^ | &)" + name + "= ([^ &] *) (& | $ )"); Var r = window. location. search. substr (1). match (reg ); If (r! = Null) return unescape (r [2]); return null; } }) (JQuery ); $ (Function (){ Alert (window. location. href ); Alert ($. getUrlParam ('page ')); }) </Script> |
Such as address:
/Front? Page = 5
When the address of a page is the above, we use the jQuery code above and a number 5 will pop up.
Attached instances
Method 1:
The Code is as follows: |
Copy code |
<Script> Function getvalue (name) { Var str = window. location. search; If (str. indexOf (name )! =-1) { Var pos_start = str. indexOf (name) + name. length + 1; Var pos_end = str. indexOf ("&", pos_start ); If (pos_end =-1) { Return str. substring (pos_start ); } Else { Return str. substring (pos_start, pos_end) } } Else { Return "No such name value "; } } Var strName = prompt ("enter the name of your desired value "); Alert (getvalue (strName )); </Script> |
Method 2:
This is the case in the eWebEditor online editor. For your reference:
The Code is as follows: |
Copy code |
Var URLParams = new Array (); Var aParams = document. location. search. substr (1). split ('&'); For (I = 0; I <aParams. length I ++ ){ Var aParam = aParams. split ('= '); URLParams [aParam [0] = aParam [1]; } // Obtain the passed name parameter Name = URLParams ["name"]; |
Method 3:
The Code is as follows: |
Copy code |
<Script type = "text/javascript"> Request = { QueryString: function (item ){ Var svalue = location. search. match (new RegExp ("[? &] "+ Item +" = ([^ &] *) (&?) "," I ")); Return svalue? Svalue [1]: svalue; } } Alert (Request. QueryString ("id ")); </Script> |