获取地址url中的query参数指定参数方法
方案一:(兼容性最好,但是有点长)
function getParam(name) {
//先获取#后面的参数
var getValue = function(name, str) {
//获取参数name的值
var reg = new RegExp("(^|!|&|\\?)" + name + "=([^&]*)(&|$)");
//再获取?后面的参数
var r = str.match(reg);
if (r != null) {
try {
return decodeURIComponent(r[2]);
} catch (e) {
console.log(e + "r[2]:" + r[2]);
return null;
}
}
return null;
};
var str = document.location.hash.substr(2);
var value = getValue(name, str);
if (value == null) {
str = document.location.search.substr(1);
value = getValue(name, str);
}
return value;
}
方案二:有兼容性(支持es6 的map就可以)
function getParams(key){
var ops = {};
window.location.href.split('?')[1].split('&').map(i => ops[(i.split('=')[0])] = i.split('=')[1]);
return ops[key]
}
方案三:有兼容性(支持es6就可以)
- ts不可用,需要改下return那行
- ?. 表示为true就继续往后执行链式
function getParams(key){
var str = window.location.href.split('?')[1].split('&').filter(i => i.startsWith(key+'='));
return str?.[0]?.split('=')[1]
}
基本上主流浏览器都没问题,一般我用万能的第一种,但是有些长