update parameters in URL with history.pushState()

2019-03-24 15:36发布

问题:

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 again with same or additional set of params. So my code looks like this:

var pageUrl = window.location.href + "?" + queryString;
window.history.pushState('','',pageUrl);

queryString is my list of query params.

  • For example, My Default page URL: http://sample.com/
  • After First AJAX call on same page URL should be: http://sample.com?param1=foo&param2=bar
  • After Second AJAX call on same page URL can be: http://sample.com/?param1=foo,foo1&param2=bar&param3=another_foo

But with the above code my params are getting appended to URL with the params and they look like below after second AJAX call:

http://sample.com?param1=foo&param2=bar&param1=foo,foo1&param2=bar&param3=another_foo

So the params appear twice in the URL, is there any way of replacing the params in URL before pushing to History or any other better way to achieve this in javascript(jquery) ?

回答1:

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

var pageUrl = '?' + queryString;
window.history.pushState('', '', pageUrl);


回答2:

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(location.search);
    params.set(name, value);
    window.history.replaceState({}, "", decodeURIComponent(`${location.pathname}?${params}`));
}