6

I'm trying to parse url in javascript, I found the following way:

var getLocation = function(href) {
    var l = document.createElement("a");
    l.href = href;
    return l;
};
var l = getLocation("http://example.com:3000/path");
var host = l.host; // example.com
var port = l.port; // 3000

But I faced a problem if these locations:

http://TLVS0015:3000/cti/YTest // the parse found the port, but its not found the host

http://ctmwe:80/ReportServer/ReportService2010.asmx // the parse found the host, but don't found the port

Is there any other way to do the parse?

3
  • Try doing l.hostname Commented Jan 14, 2015 at 10:07
  • james.padolsey.com/javascript/parsing-urls-with-the-dom Commented Jan 14, 2015 at 10:09
  • IF you have the url already, wouldn't you be better to split() and get the components? (Rather then create an object I mean) If there any perf benefits of doing it this way rather then using strings? Commented Jan 14, 2015 at 10:09

2 Answers 2

14

Source:- https://gist.github.com/jlong/2428561

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"
Sign up to request clarification or add additional context in comments.

Comments

8

If you don't need to support Internet Explorer (http://caniuse.com/#feat=url), use URL. Use hostname instead of host.

> new URL("http://TLVS0015:3000/cti/YTest").hostname
tlvs0015

The port is 80. Port 80 is default, so it is redundant, hence "".

> new URL("http://ctmwe:80/ReportServer/ReportService2010.asmx").port
""

port = URL.port === "" ? 80 : URL.port

For more information on URL(), consult the MDN API documents.

Note: as of July 2017, URL is not supported by Internet Explorer 11: http://caniuse.com/#feat=url

3 Comments

Note that URL is is an experimental feature that is not supported in Internet Explorer as of April 2015.
And continues to be as of July 2016
March 2017 - looks like it was never supported in IE, but it's in Edge 14 and 15. caniuse.com/#feat=url

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.