DEV Community 👩‍💻👨‍💻

Jordan Brennan
Jordan Brennan

Posted on • Updated on

Update current URL's query params non-destructively

Couldn't find a modern 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');

// Now update the current URL
window.history.replaceState(null, '', url); 
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)

🗣 Want to join the conversation?

 
It's easy! Become a DEV member to follow this post, comment, and more.