Explain Codes LogoExplain Codes Logo

Change URL parameters and specify defaults using JavaScript

javascript
url-parameters
javascript-utilities
url-search-params
Anton ShumikhinbyAnton Shumikhin·Feb 1, 2025
TLDR

Here's a quick way to modify query string parameters and add defaults using the URLSearchParams API:

const setURLParams = (url, updates, defaults) => { // URLSearchParams to the rescue! let searchParams = new URL(url).searchParams; // Const is jealous. But we need to change things, right? for (let [k, v] of Object.entries(defaults || {})) { searchParams.has(k) || searchParams.set(k, v); } // Don't worry, For-of. You’re not being replaced... yet! for (let [k, v] of Object.entries(updates)) { searchParams.set(k, v); } // Who needs page reloads anyway? window.history.replaceState(null, '', '?' + searchParams.toString()); }; // Action! setURLParams(location.href, {sort: 'date'}, {filter: 'active'}); // URL with updated & default params

This process encompasses all parameter operations, providing an easy and fun way to handle URLs... well, as fun as URLs can be.

Taking it further

Meet more complex scenarios with more solutions. Let's expand our URLSearchParams capabilities.

Preserving anchors

Anchors might be hidden treasures in a sea of parameters. Protect them while altering the URL:

const getWithAnchorsHandled = (url, updates) => { let [base, hash] = url.split('#'); return `${setURLParams(base, updates)}${hash ? '#' + hash : ''}`; };

Shiver me anchors! Now the SPAs are safe from being shipwrecked in the tempest of URL manipulation.

Some parameters have a more nuanced role. For them, discrimination logic can provide safe passage:

const setPageParamDefault = (url, isAll) => { let searchParams = new URL(url).searchParams; if (!searchParams.has('page') && !isAll) { searchParams.set('page', '1'); } window.history.replaceState(null, '', '?' + searchParams.toString()); };

So that's how we avoid the whirlpool of isAll and the monster of undefined page.

Polyfills for browser compatibility

URLSearchParams has a good reputation, but it has foes in ancient browsers! Equip yourself with a trustworthy polyfill for those dragon-slaying quests.

Pure JavaScript solution

For the adventurous souls who brave the wilds without light libraries or dependencies, regex is your magical artefact:

function updateParameter(url, param, value) { const re = new RegExp("([?&])" + param + "=.*?(&|$)", "i"); const separator = url.indexOf('?') !== -1 ? "&" : "?"; if (url.match(re)) { return url.replace(re, '$1' + param + "=" + value + '$2'); } else { return url + separator + param + "=" + value; } }

Wield it with care, traveller.

Visualization

Visualize setting parameters like adjusting the dials on a radio 📻. Each parameter is a dial to fine-tune your URL's emission:

// Start with the following URL 🌐 'URL=ounds&coordinates=1&frequency=100.5' // Broadcast begins setRadioParameters({ URL: 'music', coordinates: 5, frequency: 105.7}); // Now, it broadcasts 🌐 'URL=music&coordinates=5&frequency=105.7' // Sweet music to my ears

Every dial on the URL radio controls a different factor, and they can all be adjusted independently.

Juggling with falsy values

Away with falsehoods! Falsy values like 0 and '' are significant parameter values. Don't let them slip through your fingers:

const originalUrl = '...'; const paramsWithFalsyValue = { page: 0 }; setURLParams(originalUrl, paramsWithFalsyValue);

Remember, 0 isn't nothing. It's a whole number more than -1.

Web of libraries

You're not alone in this journey. Powerful helpers, like URI.js or query-string from npm offer many tools for URL manipulation.

jQuery solutions

jQuery likes the party too! Plugins like jQuery.query make URL parameter manipulation as easy as pie.

Cunning parameter handling

Craft URLs like an artisan using dynamic variables and condition-dependent parameters:

const generateDynamicUrl = (base, config) => { let url = base; Object.keys(config).forEach(key => { let value = typeof config[key] === 'function' ? config[key]() : config[key]; url = setURLParams(url, {[key]: value}); }); return url; };

Now you're not a coder. You're a URL artist.