Update current URL's query params non-destructively

Couldn't find a modern vanilla example of how to update the current URL's query params non-destructively, so I wrote this for future reference:

// Get current URL
const url = new URL(window.location.href); 

// Update or remove a param
colors.length
  ? url.searchParams.set('colors', colors.join())
  : url.searchParams.delete('colors');

// Update the URL
window.history.replaceState(null, '', url);

The URL API makes it that easy.

What's happening:

  • Gets current URL

  • Adds/removes a param without affecting any existing query params and with free encoding

  • Updates the current URL without reloading the page or adding useless history

Vanilla JS solutions like this one are best for these sorts of vanilla problems. #usetheplatform