I was looking for a way to parse a given url into hostname, port and subdomian. I got a code like this from here : How do I parse a URL into hostname and path in javascript?
var parser = document.createElement('a');
parser.href = "http://example.com:3000/pathname/?search=test#hash";
parser.protocol; // => "http:"
parser.hostname; // => "example.com"
parser.port; // => "3000"
parser.pathname; // => "/pathname/"
parser.search; // => "?search=test"
parser.hash; // => "#hash"
parser.host; // => "example.com:3000"
but here "parser.href" is given a url. Instead of that, I have a user inputed JavaScirpt variable named 'q'. I need to send the value of variable 'q' into parser.href. I tried to write simply as parser.href = q, but that didn't work.
Then I tried to implement the above as a function model through which I pass the variable q into it but that too didn't work. Here is the function:
function parseUrl(url) {
var parser = document.createElement('a');
parser.href = url;
return(parser.hostname);
}
var host = parseUrl(q);
I thought after executing the function, variable "host" will have the hostname that is returned from the function but that also didn't work. Could some one tell me how can I modify this so that it works correctly ?
Thank you so much