1.获取url所有的参数
我们可以直接通过window.location.search来取得这部分,也就是我们需要的url参数。当url没有包含?时,window.location.search会返回undefined。
function getUrlVal(str){ if(!str || str.indexOf('?') != 0) return false; var urlValArry = str.replace('?','').split('&'); var urlValObject = {}; for(var i in urlValArry){ urlValObject[urlValArry[i].split('=')[0]] = urlValArry[i].split('=')[1]; }; return urlValObject;};// https://github.com/search?utf8=%E2%9C%93&q=javascriptvar urlStr = window.location.search.replace('?','');console.log(getUrlVal(urlStr)); //输出 Object {utf8: "%E2%9C%93", q: "javascript"}
2.获取url中指定键名(name)的键值(val)
function getOneVal(str,name){ if(!str || str.indexOf('?') != 0) return false; var afterNameStr = str.replace('?','').split(name)[1]; var strFirstSite = afterNameStr.indexOf('&'); // 返回第一个&位置,如果没有'&'则返回字符串长度 strFirstSite = (strFirstSite == -1) ? afterNameStr.length : strFirstSite var reslt = afterNameStr.slice(1,strFirstSite); return reslt;};// 'http://www.gotoplay.com/active?itemtype=sport&active=basketball&time=20160614&place=N230&peopleNum=657'var urlStr = window.location.search;console.log(getOneVal(urlStr,'time')) //输出20160614console.log(getOneVal(urlStr,'peopleNum')) //657
3.利用正则表达式来获取参数( 强大的正则总是让人心生向往,利用正则无疑是最简洁优雅的一种方法)
(1)获取指定某个参数
function getUrlParam(url,name){ if(!name) return; var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i'), r = url.substr(1).match(reg); if (r != null) { return (r[2]); }else{ return null; }}
(2)获取所有的参数
function parse_url(url){ if(!url) return; var pattern = /(\w+)=(\w+)/ig; var parames = {}; url.replace(pattern, function(a, b, c){ parames[b] = c; }); return parames;}