update parameters in URL with history.pushState()

前端 未结 2 1893
离开以前
离开以前 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}`));
    }
    

提交回复
热议问题