2015-01-14 23 views
6

angularjs, şu yol buldum:Javascript url ayrıştırmak çalışıyorum javascript url Ayrıştırma veya

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 

Fakat bu yerlerin eğer bir sorunla karşı karşıya:

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 

mi var ayrıştırmayı yapmak için başka bir yol var mı?

+0

'yapmayı deneyin l.hostname' – aug

+0

http://james.padolsey.com/javascript/parsing- urls-with-the-dom/ – smarber

+0

Eğer zaten URL'niz varsa, bölme() ve bileşenleri almak daha iyi olmaz mı? (Daha sonra bir nesne yaratmak istiyorum) Eğer bu şekilde yapmanın bir yararı varsa o zaman dizeleri kullanmak yerine? – atmd

cevap

7

, URL kullanın. host yerine hostname kullanın.

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

portu 80. 80. port varsayılan olduğunu, bu yüzden dolayısıyla "" gereksiz olduğunu. URL() hakkında daha fazla bilgi için

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

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

, consult the MDN API documents.

Not: Temmuz 2017, URL itibariyle Internet Explorer tarafından desteklenmez: http://caniuse.com/#feat=url

+10

URL'nin, Nisan 2015 itibariyle Internet Explorer'da desteklenmeyen bir deneysel özellik olduğunu unutmayın. –

+0

Ve Temmuz 2016 itibariyle olmaya devam ediyor –

+0

Mart 2017 - IE'de desteklenmediği gibi görünüyor, ancak Edge 14'te ve 15. http://caniuse.com/#feat=url –

12

Kaynak: - Internet Explorer (http://caniuse.com/#feat=url) desteklemek için gerekmiyorsa 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"