Skip to content

Instantly share code, notes, and snippets.

@WesleySmits
Last active Sep 23, 2022
Embed
What would you like to do?
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