对于完整的url(包含http协议头)可使用:
const getUrlParams = (url) => {
const u = new URL(url);
const s = new URLSearchParams(u.search);
const obj = {};
s.forEach((v, k) => (obj[k] = v));
return obj;
};
对于任意字符串可使用:
const getUrlParams = (url) => {
const arrSearch = url.split('?').pop().split('#').shift().split('&');
let obj = {};
console.log(arrSearch);
arrSearch.forEach((item) => {
const [k, v] = item.split('=');
obj[k] = v;
return obj;
});
return obj;
};
判断是否有参数
export const hasParams = (url: string) => {
const arrSearch = (
url
.split('?')
?.pop()
?.split('#')
?.shift()
?.split('&') ?? []
).filter(item => item.indexOf('=') > -1);
return (arrSearch?.length ?? 0) > 0;
};
获取当前地址栏参数
export const getUrlParams = (variable: string) => {
const query = window.location.search.substring(1);
const vars = query.split("&");
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) { return pair[1]; }
}
return false;
}