Skip to content

Instantly share code, notes, and snippets.

@thackerronak
Created December 2, 2022 06:09
Show Gist options
  • Save thackerronak/0ac2af3861d7a52fba0975f67dc6c0e1 to your computer and use it in GitHub Desktop.
Save thackerronak/0ac2af3861d7a52fba0975f67dc6c0e1 to your computer and use it in GitHub Desktop.
JS/JavaScript extract query params as array from URL
/*
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