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

Community
  • 1
  • 1
user3678812
  • 417
  • 2
  • 6
  • 9

2 Answers2

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);
iamruss
  • 782
  • 4
  • 11
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);
};
Dávid Szabó
  • 2,235
  • 2
  • 14
  • 26
  • 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 – user3678812 May 28 '14 at 16:21
  • No, it always gives the right hostname, if i copy this question's url, and paste it into the input, it says stackoverflow.com – Dávid Szabó May 28 '14 at 16:59