Skip to content

Instantly share code, notes, and snippets.

@WesleySmits
Last active September 23, 2022 20:26
Show Gist options
  • Save WesleySmits/7fe92720a0353d9ba5ec9e3847ba1671 to your computer and use it in GitHub Desktop.
Save WesleySmits/7fe92720a0353d9ba5ec9e3847ba1671 to your computer and use it in GitHub Desktop.
URL Object: Compare
const baseUrl = 'https://medium.com';
const params = [
{
key: 'category',
value: 'programming'
},
{
key: 'subcategory',
value: 'front-end'
}
];
function oldWay(baseUrl, params) {
const paramString = params.reduce((prev, current, index) => {
const prefix = index === 0 ? '' : '&';
return prev + `${prefix}${current.key}=${current.value}`;
}, "?");
return baseUrl + paramString;
}
function newWay(baseUrl, params) {
const url = new URL(baseUrl);
for (param of params) {
url.searchParams.set(param.key, param.value);
}
return url.href;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment