var url_string = "http://www.example.com/t.html?a=1&b=3&c=m2-m3-m4-m5"; //window.location.href var url = new URL(url_string); var c = url.searchParams.get("c");
functionparse_query_string(query) { var vars = query.split("&"); var query_string = {}; for (var i = 0; i < vars.length; i++) { var pair = vars[i].split("="); var key = decodeURIComponent(pair[0]); var value = decodeURIComponent(pair[1]); // If first entry with this name if (typeof query_string[key] === "undefined") { query_string[key] = decodeURIComponent(value); // If second entry with this name } elseif (typeof query_string[key] === "string") { var arr = [query_string[key], decodeURIComponent(value)]; query_string[key] = arr; // If third or later entry with this name } else { query_string[key].push(decodeURIComponent(value)); } } return query_string; }
var query_string = "a=1&b=3&c=m2-m3-m4-m5"; var parsed_qs = parse_query_string(query_string); console.log(parsed_qs.c);
var query = window.location.search.substring(1); var qs = parse_query_string(query);
** 正则法 **
1 2 3 4 5 6 7 8 9 10 11
functionGetQueryString(name) { var reg = newRegExp("(^|&)"+ name +"=([^&]*)(&|$)"); var r = window.location.search.substr(1).match(reg); if(r!=null)returnunescape(r[2]); returnnull; } // 调用方法 alert(GetQueryString("参数名1")); alert(GetQueryString("参数名2"));
1 2 3 4 5 6 7 8 9
functiongup( name, url ) { if (!url) url = location.href; name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]"); var regexS = "[\\?&]"+name+"=([^&#]*)"; var regex = newRegExp( regexS ); var results = regex.exec( url ); return results == null ? null : results[1]; } gup('q', 'hxxp://example.com/?q=abc')