2015-01-14 17 views
6

Próbuję analizować URL w javascript, znalazłem następujący sposób:Przetwarzanie url w javascript lub angularjs

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 

Ale pojawił się kolejny problem, jeśli te lokalizacje:

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 

Czy istnieje w inny sposób zrobić parsę?

+0

Spróbuj zrobić 'l.hostname' – aug

+0

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

+0

JEŻELI masz już adres URL, czy nie lepiej byłoby podzielić() i pobrać komponenty? (Zamiast tego stwórz obiekt, który mam na myśli) Jeśli istnieją jakieś zalety płynące z robienia tego w ten sposób, a nie za pomocą łańcuchów? – atmd

Odpowiedz

7

Jeśli nie muszą wspierać Internet Explorer (http://caniuse.com/#feat=url), użyj URL. Użyj hostname zamiast host.

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

Port jest 80. Port 80 jest domyślnym, więc to jest zbędne, stąd "".

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

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

Aby uzyskać więcej informacji na URL(), consult the MDN API documents.

Uwaga: od lipca 2017, URLnie jest obsługiwany przez program Internet Explorer 11: http://caniuse.com/#feat=url

+10

Należy zauważyć, że "URL" jest eksperymentalną funkcją, która nie jest obsługiwana w Internet Explorerze od kwietnia 2015. –

+0

I nadal jest w lipcu 2016 roku –

+0

Marzec 2017 - wygląda na to, że nigdy nie była obsługiwana w IE, ale jest w Edge 14 i 15. http://caniuse.com/#feat=url –

12

Źródło: - 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"