Question: How to properly get the parameters from a URL with ampersand symbols?
Context: I'm trying to figure out why is it the result from iTunes Store Webservice returns different data when removing amp;. I'm using this diff tool: https://www.diffnow.com/compare-urls
Original URL:
https://itunes.apple.com/search?term=star&country=au&media=movie&all
What's more confusing to me is the all value in the url. Based on the doc of iTunes Store Webservice, it's either an attribute
or entity
.
But regardless, I still get different result. To reiterate,
the original url:
https://itunes.apple.com/search?term=star&country=au&media=movie&all
returns different data for the following:
a. https://itunes.apple.com/search?term=star&country=au&media=movie&attribute=all
b. https://itunes.apple.com/search?term=star&country=au&media=movie&entity=all
c. https://itunes.apple.com/search?term=star&country=au&media=movie&all
You can create a small helper and use the URL constructor to get an object representing the URL defined by the parameters.
From this object, we're going to get the search property that it's the query string and replace the &
to &
.
function getItunesParameters(url) {
const { search } = new URL(url);
const parsedQuery = search.replace(/&/g, '&');
return parsedQuery;
}
getItunesParameters('https://itunes.apple.com/search?term=star&country=au&media=movie&all');
// => "?term=star&country=au&media=movie&all"
Optionally you can return an object if it's easy for you to handle afterwards
function getItunesParameters(url) {
const { search } = new URL(url);
const parsedQuery = search.replace(/&/g, '&');
return parsedQuery
.slice(1)
.split('&')
.reduce((acc, query) => {
const [key, value] = query.split('=');
return { ...acc, [key]: value || '' };
}, {});
}
getItunesParameters('https://itunes.apple.com/search?term=star&country=au&media=movie&all'); //?
// => {term: "star", country: "au", media: "movie", all: ""}
Good luck!