Last active
February 18, 2025 09:23
-
-
Save john-doherty/cdbb87ddba438f4bf5af58821f8a03e7 to your computer and use it in GitHub Desktop.
Add query string parameters to a URL in JavaScript (works with browser/node, merges duplicates and works with absolute and relative URLs)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Adds query params to existing URLs (inc merging duplicates) | |
* @param {string} url - src URL to modify | |
* @param {object} params - key/value object of params to add | |
* @example | |
* // returns /guides?tag=api | |
* addQueryParamsToUrl('/guides?tag=hardware', { tag:'api' }) | |
* @example | |
* // returns https://orcascan.com/guides?tag=api | |
* addQueryParamsToUrl('https://orcascan.com/guides?tag=hardware', { tag: 'api' }) | |
* @returns {string} modified URL | |
*/ | |
function addQueryParamsToUrl(url, params) { | |
// if URL is relative, we'll need to add a fake base | |
var fakeBase = !url.startsWith('http') ? 'http://fake-base.com' : undefined; | |
var modifiedUrl = new URL(url || '', fakeBase); | |
// add/update query params | |
Object.keys(params).forEach(function(key) { | |
if (modifiedUrl.searchParams.has(key)) { | |
modifiedUrl.searchParams.set(key, params[key]); | |
} | |
else { | |
modifiedUrl.searchParams.append(key, params[key]); | |
} | |
}); | |
// return as string (remove fake base if present) | |
return modifiedUrl.toString().replace(fakeBase, ''); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment