Js gets the parameter name and parameter value in the url. js gets the url parameter
It is rare to use js to obtain the parameter name and parameter value in the url, but I need to do so today. Next I will introduce the specific instance method.
When the parameter name is known, it is easy to obtain the parameter value using a regular expression.
The js implementation method is as follows:
| The Code is as follows: |
Copy code |
Function getValue (url, name ){ Var reg = new RegExp ('(\? | &) '+ Name +' = ([^ &?] *) ',' I '); Var arr = url. match (reg ); If (arr ){ Return arr [2]; } Return null; } |
Or
Method 1: Regular Expression Analysis
| The Code is as follows: |
Copy code |
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 this method as follows: Alert (GetQueryString ("parameter name 1 ")); Alert (GetQueryString ("parameter name 2 ")); Alert (GetQueryString ("parameter name 3 ")); |
If you want to obtain all the parameter names and their corresponding values, you can also use the regular expression method,
Js implementation method:
| The Code is as follows: |
Copy code |
Function getKeyValue (url ){ Var result = {}; Var reg = new RegExp ('([\? | &]) (. + ?) = ([^ &?] *) ', 'Ig '); Var arr = reg.exe c (url ); While (arr ){ Result [arr [2] = arr [3]; Arr = reg.exe c (url ); } Return result; } |
Note that in js, another method for matching is match. match is a string method, while exec is a RegExp object method. If you use the string match method and the regular expression is specified as a global match, grouping in the regular expression is useless. The returned results are all substrings that match the regular expression. When the exec method does not use the global match flag, the first matched sub-character is returned. If the global match flag is used, the string that matches the symbol from the beginning is executed for the first time and called again, the match starts from the last matching result.
The following describes how to implement php:
| The Code is as follows: |
Copy code |
Function getKeyValue ($ url ){ $ Result = array (); $ Mr = preg_match_all ('/(? | &) (. + ?) = ([^ &?] *)/I ', $ url, $ matchs ); If ($ mr! = FALSE ){ For ($ I = 0; $ I <$ mr; $ I ++ ){ $ Result [$ matchs [2] [$ I] = $ matchs [3] [$ I]; } } Return $ result; } |
The preg_match_all method of php stores the matching results in the third specified parameter, which is a two-dimensional array. The first dimension is the array of group information, that is, the first array stores all matching complete strings, and the second array stores the corresponding values of the first, the second dimension is the group value.