0

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

2 Answers 2

1

It already works!

Checkout this fiddle

function parseUrl(url) {
    var parser = document.createElement('a');
    parser.href = url;
  return(parser.hostname);
}

var host = parseUrl('http://example.com:3000/pathname/?search=test#hash');
document.write(host);
Sign up to request clarification or add additional context in comments.

Comments

0

It does work for me.

http://jsfiddle.net/rFYYv/

   function parseUrl(url) {
        var parser = document.createElement('a');
        parser.href = url;
      return(parser.hostname);
   }

var output = document.getElementById('output');
var input = document.getElementById('input');

input.onkeyup = function(e) {
    output.innerHTML = parseUrl(input.value);
};

2 Comments

Your fiddle always returns the answer "fiddle.jshell.net" no matter what the inout you gives right ? that is the same problem that I am facing. I am getting the hostname of the site in which I implement this instead of the hostname of the url saved in the javascript variable
No, it always gives the right hostname, if i copy this question's url, and paste it into the input, it says stackoverflow.com

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.