DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 963,673 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
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)

"I made 10x faster JSON.stringify() functions, even type safe"

☝️ Must read for JS devs