Here's a JavaScript solution. By using the URL
constructor on the link, you can easily access its parameters.
const urlParamsToObject = (link) => {
const url = new URL(link);
return Object.fromEntries(url.searchParams.entries());
};
console.log(urlParamsToObject('http://www.apple.com?a=1&b=2&c=3'));
Is this really an Apple interview question?
EDIT:
It's also possible to do this without the URL constructor. Here's an example of that in TypeScript:
const urlParamsToObject = (link: string) => {
const searchParams = link.split('?')[1].split('&');
return searchParams.reduce<Record<string, string>>((acc, curr) => {
const [key, val] = curr.split('=');
return {
...acc,
[key]: decodeURIComponent(val),
};
}, {});
};
console.log(urlParamsToObject('http://www.apple.com?a=1&b=2&c=3'));
And here's an example in Python:
from urllib.parse import unquote
def url_to_params_object (link: str):
search_params = link.split('?')[1].split('&')
return { str.split('=')[0]: unquote(str.split('=')[1]) for str in search_params }
print(url_to_params_object('http://www.apple.com?a=1&b=2&c=3'))