Before modification:
Copy codeThe Code is as follows:
<Script type = "text/javascript">
Var url = "www.taobao.com? Key0 = a & key1 = B & key2 = c ";
Function parseQueryString (url ){
Var str = url. split ("? ") [1],
Items = str. split ("&");
Var arr, name, value;
For (var I = 0, l = items. length; I <l; I ++ ){
Arr = items [I]. split ("= ");
Name = arr [0];
Value = arr [1];
This [name] = value;
}
}
Var obj = new parseQueryString (url );
Alert (obj. key1)
</Script>
After modification:
Copy codeThe Code is as follows:
<Script type = "text/javascript">
Var url = "www.taobao.com? Key0 = a & key1 = B & key2 = c ";
Var pQString = {
CreateNew: function (url ){
Var str = url. split ("? ") [1],
Items = str. split ("&");
Var arr, name, value;
For (var I = 0, l = items. length; I <l; I ++ ){
Arr = items [I]. split ("= ");
Name = arr [0];
Value = arr [1];
This [name] = value;
}
}
}
Var obj = new pQString. createNew (url );
Alert (obj. key1)
</Script>
Thanks to the grass-roots programmers for rewriting this method. It is more rigorous and efficient. I will study it later !!!
Copy codeThe Code is as follows:
<Script type = "text/javascript">
Function getQueryString (url ){
If (url ){
Url = url. substr (url. indexOf ("? ") + 1); // string truncation, which is more efficient than my previous split () method
}
Var result = {}, // create an object for storing name, and value
QueryString = url | location. search. substring (1), // location. search sets or returns the question mark (?) The start url (query part ).
Re =/([^ & =] +) = ([^ &] *)/g, // regular, not used
M;
While (m = re.exe c (queryString) {// exec () Regular Expression matching, not used
Result [decodeURIComponent (m [1])] = decodeURIComponent (m [2]); // use decodeURIComponent () to decode the encoded URI.
}
Return result;
}
// Demo
Var myParam = getQueryString ("www.taobao.com? Key0 = a & key1 = B & key2 = c ");
Alert (myParam. key1 );
</Script>
Note:
1. substr () and substring (start, stop) are used to extract characters that are intermediary between two specified subscripts.
Important: Unlike slice () and substr (), substring () does not accept negative parameters.
See http://www.jb51.net/w3school/js/jsref_substring.htm
2. location. search. substring (1), location. search sets or returns the question mark (?) The start url (query part ).
See http://www.jb51.net/w3school/htmldom/prop_loc_search.htm
3. the exec () method is used to retrieve the matching of regular expressions in a string. Too powerful to use
Reference http://www.jb51.net/w3school/js/jsref_exec_regexp.htm
4. decodeURIComponent () is used to decode the encoded URI.
See http://www.jb51.net/w3school/js/jsref_exec_regexp.htm