在附加url参数之前删除查询字符串

时间:2018-05-02 16:17:30

标签: javascript jquery html query-string

我想在添加网址参数之前从网址中删除查询字符串。假设我的网站是https://www.abcd.com/test我将一些参数附加到我的网址,例如/ def?key = value通过javascript。但该页面构建为https://www.abcd.com/test?/def?key=value。我希望它是https://www.abcd.com/test/def?key=value以下是我的代码。任何意见都非常感谢。

redirectURL: function() {
    var currentURL = window.location.href;

    var kvp = document.location.search.substr(1).split('&');
    if (kvp == '') {
        if (currentURL.indexOf("def") == -1){ 
            document.location.search = '/def'+ '?' + 'key' + '=' + 'value';
        }else{
            document.location.search = '?' + 'key' + '=' + 'value';
        }
    }
    else {
        var i = kvp.length; var x; while (i--) {
            x = kvp[i].split('=');

            if (x[0] == key) {
                x[1] = value;
                kvp[i] = x.join('=');
                break;
            }
        }

        if (i < 0) { kvp[kvp.length] = [key, value].join('='); }

        document.location.search = kvp.join('&');
    }
}

1 个答案:

答案 0 :(得分:0)

您正在将网址参数附加到location.search属性,即查询字符串:

document.location.search = '/def'+ '?' + 'key' + '=' + 'value';

我相信您要做的是将网址参数附加到location.href属性,但首先您需要将现有的search字符串(查询字符串)与它:

var urlBase = window.location.href.split('?')[0];
window.location.href = urlBase + '/def'+ '?' + 'key' + '=' + 'value';