js 更新url链接地址(在地址上添加/修改参数)

  1. 更新链接参数方法:

function updateParameter(url, key, value) {
    if(value==undefined||value==null) {
         return url;
    };
    var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
    var separator = url.indexOf('?') !== -1 ? "&" : "?";
    if (url.match(re)) {
        return url.replace(re, '$1' + key + "=" + value + '$2');
    }
    else {
        return url + separator + key + "=" + value;
    }
};

用法:

var newurl=updateParameter(window.location.href,'areaCode','A');

  1. 更新替换地址方法:

function updateWindowUrl(key,value){
    var newurl = updateParameter(window.location.href,key, value);
    window.history.replaceState({
        path: newurl
    }, '', newurl);
};

用法:updateWindowUrl('areaCode','B');链接上的areaCode参数的值被替换为B。

猜你喜欢

转载自blog.csdn.net/pinhmin/article/details/129086711