Change URL parameters

前端 未结 26 2457
孤独总比滥情好
孤独总比滥情好 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 08:54

    Quick little solution in pure js, no plugins needed:

    function replaceQueryParam(param, newval, search) {
        var regex = new RegExp("([?;&])" + param + "[^&;]*[;&]?");
        var query = search.replace(regex, "$1").replace(/&$/, '');
    
        return (query.length > 2 ? query + "&" : "?") + (newval ? param + "=" + newval : '');
    }
    

    Call it like this:

     window.location = '/mypage' + replaceQueryParam('rows', 55, window.location.search)
    

    Or, if you want to stay on the same page and replace multiple params:

     var str = window.location.search
     str = replaceQueryParam('rows', 55, str)
     str = replaceQueryParam('cols', 'no', str)
     window.location = window.location.pathname + str
    

    edit, thanks Luke: To remove the parameter entirely, pass false or null for the value: replaceQueryParam('rows', false, params). Since 0 is also falsy, specify '0'.

提交回复
热议问题