Created
December 2, 2022 06:09
-
-
Save thackerronak/0ac2af3861d7a52fba0975f67dc6c0e1 to your computer and use it in GitHub Desktop.
JS/JavaScript extract query params as array from URL
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
/* | |
Input : https://www.amazon.com/s?k=mac+book&crid=25WTZ65PMNIO8&sprefix=mac+book%2Caps%2C278&ref=nb_sb_noss_2 | |
Output : | |
[ | |
{ | |
"k": "mac+book" | |
}, | |
{ | |
"crid": "25WTZ65PMNIO8" | |
}, | |
{ | |
"sprefix": "mac+book%2Caps%2C278" | |
}, | |
{ | |
"ref": "nb_sb_noss_2" | |
} | |
] | |
*/ | |
const url = new URL( | |
"https://www.amazon.com/s?k=mac+book&crid=25WTZ65PMNIO8&sprefix=mac+book%2Caps%2C278&ref=nb_sb_noss_2" | |
); | |
const parameters = url.search | |
? url.search | |
.slice(1) | |
.split("&") | |
.map((p) => p.split("=")) | |
.reduce((obj, [key, value]) => [...obj, value && { [key]: value }], []) | |
: []; | |
console.log(JSON.stringify(parameters)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment