Parsing URLs in javascript or angularjs

I am 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 ran into 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 parsing?

+6
source share
2 answers

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

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

Port 80. Port 80 is the 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() , refer to the MDN API docs .

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

+7
source

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" 
+12
source

Source: https://habr.com/ru/post/980982/


All Articles