首页 > Web开发 > 详细

js: url相关方法

时间:2020-07-09 13:17:29      阅读:52      评论:0      收藏:0      [点我收藏+]

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
}

 

js: url相关方法

原文:https://www.cnblogs.com/Nyan-Workflow-FC/p/13272944.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!