Explain Codes LogoExplain Codes Logo

How can I add or update a query string parameter?

javascript
url-management
query-string-parameters
url-search-params
Nikita BarsukovbyNikita Barsukov·Jan 14, 2025
TLDR

You can immediately set or update a query parameter using URLSearchParams:

const url = new URL(window.location); url.searchParams.set('key', 'newValue'); // Like giving a new value to an old comrade! window.history.pushState({}, '', url);

But, when URLSearchParams goes AWOL (is not supported), backup arrives with a succinct function leveraging regular expressions:

function updateQuery(uri, key, value) { let re = new RegExp("([?&])" + key + "=[^&]*"); // Crafting the Regex Weapon if (uri.match(re)) { return uri.replace(re, '$1' + key + '=' + value); // Updating existing soldier } else { return uri + (uri.indexOf('?') === -1 ? '?' : '&') + key + '=' + value; // Welcome to our new recruit! } } window.history.pushState({}, '', updateQuery(window.location.href, 'key', 'newValue'));

Whichever method you use, you're sure to modify the URL without reloading the page!

Battle-hardened URL practices

To navigate this battlefield known as URL management, adhere to these well-known tactics:

Adjust for dynamic changes

Make sure to handle dynamic data comfortably. We want our URLs to be like a well-coordinated battalion, capable of updating query parameters without falling into disarray.

Do a recon before any changes

Carrying out recon is crucial, even with query parameters. Always check their existence before adding or updating. This protects you from duplicates, and keeps your data mission-ready!

Separator, the silent hero

Correct usage of "?" and "&" separators is imperative for maintaining unity in your URL. It's the little things that keep your battalion moving.

The URL minefield: Edge Cases

But, a battlefield isn’t devoid of mines, and here are some you may encounter:

Encoding the intel

When dealing with special characters or spaces, use encodeURIComponent to encrypt them safely:

url.searchParams.set('key', encodeURIComponent('new Value')); // Encrypting our secret message!

Old allies: Cross-browser compatibility

Although our trusty companion URLSearchParams is a veteran, some older browsers might not recognize it. A polyfill is what you need to bridge this gap.

Decoding arrays and objects

When you find an unknown package, like arrays or objects in your query strings, thoroughly serialize before storing and neatly parse when retrieving.

Abandoning the base

To tactically retreat and remove a query parameter, use URLSearchParams.delete:

url.searchParams.delete('key'); // Tactical withdrawal! window.history.pushState({}, '', url);

Planning the next move: History management

Fail, but don't leave a trace

Use history.replaceState if you're reconning and need to change the URL without leaving footprints in the history:

window.history.replaceState({}, '', url); // A change, but shhh! It never happened!

Retreating with honor

When the order is to retreat and the change entails navigation, sound the location.assign or location.replace bugles accordingly.

Protect the mission code

Guard the hash tags like the precious mission codes they are when updating URLs!

Your intel: References

Ensure to study MDN documentation and run drills on online code playgrounds like JSFiddle. Additionally, trusty allies on GitHub or npm offer ready-to-use libraries that streamline your mission.