update parameters in URL with history.pushState()

前端 未结 2 1895
离开以前
离开以前 2021-02-05 05:02

I am using history.pushState to append few params to current page URL after making an AJAX call on my page. Now on same page based on user action, I want to update the page URL

相关标签:
2条回答
  • 2021-02-05 05:40

    This function might be helpful

    function updateUrlParameter(param, value) {
        const regExp = new RegExp(param + "(.+?)(&|$)", "g");
        const newUrl = window.location.href.replace(regExp, param + "=" + value + "$2");
        window.history.pushState("", "", newUrl);
    }
    

    Edit: The following solution is simpler, and it also works if the parameter is not yet part of the URL. However, it's not supported by Internet Explorer (you don't say?).

    function setQueryStringParameter(name, value) {
        const params = new URLSearchParams(window.location.search);
        params.set(name, value);
        window.history.replaceState({}, "", decodeURIComponent(`${window.location.pathname}?${params}`));
    }
    
    0 讨论(0)
  • 2021-02-05 05:48

    I think what you need is remove window.location.href and leave '?' +.

    var pageUrl = '?' + queryString;
    window.history.pushState('', '', pageUrl);
    
    0 讨论(0)
提交回复
热议问题