Js decomposition url parameters (regular expressions, split comparison) (Object-Oriented-simple method), simple split
I. Regular Expression
<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 saving 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, m is not used; while (m = re.exe c (queryString) {// exec () Regular Expression matching, not using 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
Ii. split method (COPY on javascript guide .)
/* * This function parses ampersand-separated name=value argument pairs from * the query string of the URL. It stores the name=value pairs in * properties of an object and returns that object. Use it like this: * * var args = getArgs( ); // Parse args from URL * var q = args.q || ""; // Use argument, if defined, or a default value * var n = args.n ? parseInt(args.n) : 10; */ function getArgs( ) { var args = new Object( ); var query = location.search.substring(1); // Get query string var pairs = query.split("&"); // Break at ampersand for(var i = 0; i < pairs.length; i++) { var pos = pairs[i].indexOf('='); // Look for "name=value" if (pos == -1) continue; // If not found, skip var argname = pairs[i].substring(0,pos); // Extract the name var value = pairs[i].substring(pos+1); // Extract the value value = decodeURIComponent(value); // Decode it, if needed args[argname] = value; // Store as a property } return args; // Return the object }