Please offers JavaScript language solution
Here is the Apple interview question:
input: http://www.apple.com?a=1&b=2&c=3
output:
{
a:1,
b:2,
c:3
}
How to solve this question without hard code? and
If I don't know URL constructor concept, any other solution to solve this problem?
CodePudding user response:
That part of the URL you're looking for is called query string. There are lots of libraries in programming languages that can parse the URL and get those parameters.
Here is a Python solution:
With urllib.parse
module you can parse(urlparse
) a URL and get the information from its query string(parse_qs
).
from urllib.parse import urlparse, parse_qs
url = "http://www.apple.com?a=1&b=2&c=3"
parsed_url = urlparse(url)
d = {k: v[0] for k, v in parse_qs(parsed_url.query).items()}
print(d)
output:
{'a': '1', 'b': '2', 'c': '3'}
the [0]
part is because the values of the dictionary returned from the parse_qs
is a list. So we get its (first) item.
CodePudding user response:
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?