获取url参数,删除url参数,添加url参数

const url = `http://localhost:7127/dashboard/workplace?a=123&b=456&c=789`
// 获取URL参数
function getParams(url) {
    var strs;
	var url = url || window.location.href; //获取url中"?"符后的字串
	var theRequest = new Object();
	if (url.indexOf("?") != -1) {
		url = url.substr(url.indexOf("?"));
		var str = url.substr(1);
		strs = str.split("&");
		for (var i = 0; i < strs.length; i++) {
			var index = strs[i].indexOf("=");
			theRequest[strs[i].slice(0, index)] = unescape(strs[i].slice(index + 1, strs[i].length));
		}
	}
	return theRequest;
}
console.log(‘获取url参数‘,JSON.stringify(getParams(url)))

// 删除URL参数
function delParam(paramKey,myurl) {
	var url = myurl || window.location.href; //页面url
    var urlParam = window.location.search.substr(1); //页面参数
    if(myurl && url.indexOf("?")>-1) {
        urlParam = url.substr(url.indexOf("?")+1,url.length); 
    } else {
        return url
    }

    // 主页面地址(参数之前地址)
	var beforeUrl = url.substr(0, url.indexOf("?")); 

    // 参数(主地址后面)
	var nextUrl = "";

    // 
	var arr = new Array();
	if (urlParam != "") {
		var urlParamArr = urlParam.split("&"); //将参数按照&符分成数组
		for (var i = 0; i < urlParamArr.length; i++) {
            //将参数键,值拆开
			var paramArr = urlParamArr[i].split("="); 
			//如果键雨要删除的不一致,则加入到参数中
			if (paramArr[0] != paramKey) {
				arr.push(urlParamArr[i]);
			}
		}
	}

    // 构造参数字符串
	if (arr.length > 0) {
		nextUrl = "?" + arr.join("&");
	}

    // 拼接
	url = beforeUrl + nextUrl;
	return url;
}
console.log(‘删除url参数‘,delParam(‘b‘,url))

// 添加URL参数
function addParams(params,myurl) {
    var url = myurl || window.location.href; //页面url
    var arr = new Array()
    var nextUrl = ‘‘
    Object.keys(params).map(item => {
        arr.push(`${item}=${params[item]}`)
    })
    if(url.indexOf(‘?‘)>-1) {
        nextUrl = "&" + arr.join("&");
    } else {
        nextUrl = "?" + arr.join("&");
    }
    return url + nextUrl
}

console.log(‘添加url参数‘,addParams({d:135,e:246},url))

获取url参数,删除url参数,添加url参数

上一篇:html中写带圈的数字


下一篇:Anaconda + Djongo + spyder 网站开发 (三)