Ramzy Abourafeh
Ramzy Abourafeh

Reputation: 1195

Parsing url in javascript or angularjs

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?

Upvotes: 6

Views: 11505

Answers (2)

Bas Dirks
Bas Dirks

Reputation: 411

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

Upvotes: 8

squiroid
squiroid

Reputation: 14017

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"

Upvotes: 14

Related Questions