Change URL parameters

前端 未结 26 2190
孤独总比滥情好
孤独总比滥情好 2020-11-22 08:40

I have this URL:

site.fwx?position=1&archiveid=5000&columns=5&rows=20&sorting=ModifiedTimeAsc

what I need is to be able to

26条回答
  •  醉话见心
    2020-11-22 09:09

    2020 Solution: sets the variable or removes iti if you pass null or undefined to the value.

    var setSearchParam = function(key, value) {
        if (!window.history.pushState) {
            return;
        }
    
        if (!key) {
            return;
        }
    
        var url = new URL(window.location.href);
        var params = new window.URLSearchParams(window.location.search);
        if (value === undefined || value === null) {
            params.delete(key);
        } else {
            params.set(key, value);
        }
    
        url.search = params;
        url = url.toString();
        window.history.replaceState({url: url}, null, url);
    }
    

提交回复
热议问题