Come ottenere un sottodominio utilizzando window.location?
-
05-07-2019 - |
Domanda
Se ho un nome host come: http://sample.example.com e in Javascript I fare window.location.hostname
, otterrei " example.com " o " sample.example.com " ;?
In caso contrario, come potrei ottenere sample.example.com?
Soluzione
Sì, window.location.hostname
ti darà anche i sottodomini. Se non funziona o non è supportato da altri browser, puoi analizzarlo facilmente:
// window.location.href == "http://sample.somedomain.com/somedir/somepage.html"
var domain = /:\/\/([^\/]+)/.exec(window.location.href)[1];
Altri suggerimenti
Prima di tutto, è window.location
, non document.location
( document.location
funziona in alcuni browser ma non è standard )
E sì, location.hostname
restituirà l'intero nome di dominio, inclusi eventuali sottodomini
Leggi di più qui
Può essere fatto come di seguito:
var subdomain = window.location.host.split('.')[1] ? window.location.host.split('.')[0] : false;
Sì, l'avviso (window.location.hostname) includerà sottodomini come "www" e "sample".
Che ne dici di questo frammento. Potrebbe aiutare:
var a = new String(window.location);
a = a.replace('http://','');
a = a.substring(0, a.indexOf('/'));
alert(a);
Questo è il trucco per me:
var host = window.location.host
var subdomain = host.split('.’)[0]