js对url指定参数进行删除,并返回url

2024年07月30日 建站教程

1、删除当前页面的url中flag参数

function urlDel(name){
	var url = window.location;
	var baseUrl = url.origin + url.pathname + "?";
	var query = url.search.substr(1);
	if (query.indexOf(name)>-1) {
		var obj = {}
		var arr = query.split("&");
		for (var i = 0; i < arr.length; i++) {
			arr[i] = arr[i].split("=");
			obj[arr[i][0]] = arr[i][1];
		};
		delete obj[name];
		var url = baseUrl + JSON.stringify(obj).replace(/[\"\{\}]/g,"").replace(/\:/g,"=").replace(/\,/g,"&");
		return url
	}else{
		return window.location.href;
	};
}
//控制台输出
console.log(funcUrlDel('flag'));

2、删除特定的url链接中的flag参数

function urlDelParams(url,name){
	var urlArr = url.split('?');
	if(urlArr.length>1 && urlArr[1].indexOf(name)>-1){
		var query = urlArr[1];
		var obj = {}
		var arr = query.split("&");
		for (var i = 0; i < arr.length; i++) {
			arr[i] = arr[i].split("=");
			obj[arr[i][0]] = arr[i][1];
		};
		delete obj[name];
		var urlte = urlArr[0] +'?'+ JSON.stringify(obj).replace(/[\"\{\}]/g,"").replace(/\:/g,"=").replace(/\,/g,"&");
		return urlte;
	}else{
		return url;
	};
}
//控制台输出
console.log(urlDelParams('http://lmcjl.com/?flag=1&lan=cn', 'flag'))

本文链接:http://so.lmcjl.com/news/9541/

展开阅读全文