Add a get parameter to the current URL with JavaScript

Published on 2019-02-27 • Modified on 2019-02-27

Here is a clean way to do this using the URL JavaScript object. In this snippet, 1) We get the current URL 2) We create an URL object with the current url we've just retrieved. 3) we apprend and set get parameters to it. 4) Then, we change the current url of the browser without reloading the page. Et voilà! 😉

PS: Note that if you hit the refresh button of your browser, the id parameter will be append another time, not the foo parameter because we use the set function that prevents it from being added more than one time. (so most of the time we just need the set function)

    let urlStr = window.location.href;
    let urlObj = new URL(urlStr);
    urlObj.searchParams.append('foo', 'bar');
    urlObj.searchParams.append('id', '17');
    urlObj.searchParams.set('foo', 'bar2');
    history.replaceState({}, "", urlObj.toString());