Skip to content

Instantly share code, notes, and snippets.

@john-doherty
Last active January 18, 2022 23:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save john-doherty/cdbb87ddba438f4bf5af58821f8a03e7 to your computer and use it in GitHub Desktop.
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)
/**
* 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