URL Object: Compare
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
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