获取url上的参数
假如url是这样的: 要取得参数a的值11 和 b 的值 2。
http://qiandu.com?a=11&b=&c=3
首先要知道url带的参数都在?后面的查询串,有两种方法可以获取
1.location.search 直接获取查询串
location.search = '?a=11&b=&c=3'
2.location.href 和 split 函数取得查询串(但这种方法当hash串或有两个以上的?时需要另外处理,不推荐使用)
得到查询字串后就能使用正则来得到想要的参数了
1.url参数是key=value
组合,所以验证规则是:参数名=参数值 ,参数名动态获得,参数值可以是任意合法的url字符,
任意字符用符号.
(匹配除换行符 \n 之外的任何单字符)表示。
function getParam(name){
let search = location.search;
let reg = new RegExp(name + '=.');
let res = search.match(reg);
}
但.
只能匹配一次,匹配多次要用 符号*
(匹配0次或多次)。
function getParam(name){
let search = location.search;
let reg = new RegExp(name + '=.*');
let res = search.match(reg);
}
另外我们希望单独得到参数值,不掺杂其他匹配到的字符,那么要用到分组符()
(将分组的字符以单独的项出现在匹配结果中)。
function getParam(name){
let search = locatiosn.search;
let reg = new RegExp(name + '=(.*)');
let res = search.match(reg);
return res[1]
}
// 获取参数a
getParam(a); // 11&b=&c=3
2.这里看到把a参数值后面的一串都取出来了,因为.*
匹配了多次字符,那就需要在适当的位置来终止匹配。由于每个key=value是用&来连接的。这里的终止符就是&。但.
匹配的是任意字符呀,所以得寻找最近的&,就要用到*?
组合(非贪婪模式,即匹配到最近的&)
注:最后一个参数后没有&,那么匹配一个结束符$
function getParam(name){
let search = location.search;
let reg = new RegExp(name + '=(.*?)(&|$)');
let res = search.match(reg);
return res?res[1]:null
}
// 获取参数
getParam(a); // 11
getParam(b); // ''
getParam(c); // 3
但问题又来了,当参数出现又重叠字符的时候(如:?uid=x&sid=y&id=z)。匹配id
时就会取到uid
的值。因为上面只做了尾部处理,没做开头处理,这里就要匹配参数的开始字符。把?
处理掉,那么参数的开端只能是开始位置或链接符(^|&)
function getParam(name){
let search = location.search.replace(/\?/,'')
let reg = new RegExp('(^|&)' + name + '=(.*?)(&|$)');
let res = search.match(reg);
return res?res[2]:null; // 参数值的分组钱多了一个分组,下标往后移1
}
现在参数名称是全匹配时才能取到它的值。