js: url相关方法
1、获取url参数
getUrlParam = function (string) { var reg = new RegExp("(^|&)" + string + "=([^&]*)(&|$)"); var d = window.location.href.split('?'); if (d.length > 1) { var r = d[1].match(reg); if (r) { return decodeURI(r[2]); } } return null; };
getHashParam(name) { var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"), queryString = window.location.hash.split('?')[1] || '', result = queryString.match(reg); return result ? decodeURIComponent(result[2]) : null; }
getParam(name) { var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"), queryString = window.location.search.split('?')[1] || '', result = queryString.match(reg); return result ? decodeURIComponent(result[2]) : null; }
2、登陆后跳转登录前地址
// 跳转登录 doLogin() { let loginUrl = '/login?redirect=' + encodeURIComponent(window.location.pathname); window.location = loginUrl; }
3、转换参数与url
加密及解密
export const encodeParam = (param: any) => { return btoa(encodeURIComponent(JSON.stringify(param))); } export const decodeParam = (encodeParam: any) => { return JSON.parse(decodeURIComponent(atob(encodeParam))); }
互相转换
export const toUrlParam = (param: any): string => { if (typeof param !== "object") return; let urlParam = ""; for (const key in param) { if (param.hasOwnProperty(key)) { urlParam = urlParam + `&${key}=${encodeParam(param[key])}` } } return urlParam; } export const transferUrlParam = (urlParam: string) => { if (urlParam.indexOf("?") !== -1) { urlParam = urlParam.substring(1); } let param = {}; const urlParams = urlParam.split("&"); urlParams.forEach(item => { const itemArr = item.split("="); param[itemArr[0]] = itemArr[1]; }); return param }