1. 程式人生 > >js 對url進行某個引數的刪除,並返回url

js 對url進行某個引數的刪除,並返回url

兩種情況

1對當前頁面的url進行操作

function funcUrlDel(name){
        var loca = window.location;
        var baseUrl = loca.origin + loca.pathname + "?";
        var query = loca.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('tt'));

2 對特定的url進行處理

function urlDelP(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(urlDelP('http://test.com/test?tt=3&kk=6','tt'));
console.log(urlDelP('http://test.com/test?kk=6&ll=88','tt'));