Parsing url in javascript or angularjs
11,411
Solution 1
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
Solution 2
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"
Author by
Ramzy Abourafeh
Updated on June 27, 2022Comments
-
Ramzy Abourafeh almost 2 years
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?
-
Adam C about 9 yearsNote that
URL
is is an experimental feature that is not supported in Internet Explorer as of April 2015. -
Ian Clark almost 8 yearsAnd continues to be as of July 2016
-
Jeremy Wadhams about 7 yearsMarch 2017 - looks like it was never supported in IE, but it's in Edge 14 and 15. caniuse.com/#feat=url