¿Cómo obtener un subdominio usando window.location?
-
05-07-2019 - |
Pregunta
Si tengo un nombre de host como: http://sample.example.com y en Javascript I haga window.location.hostname
, obtendría " example.com " o " sample.example.com " ;?
Si no, ¿cómo podría obtener sample.example.com?
Solución
Sí, window.location.hostname
también te dará subdominios. Si esto no funciona, o si no es compatible con algún otro navegador, podría analizarlo fácilmente:
// window.location.href == "http://sample.somedomain.com/somedir/somepage.html"
var domain = /:\/\/([^\/]+)/.exec(window.location.href)[1];
Otros consejos
En primer lugar, es window.location
, no document.location
( document.location
funciona en algunos navegadores, pero no es estándar )
Y sí, location.hostname
devolverá el nombre de dominio completo, incluidos los subdominios
Lee más aquí
Se puede hacer de la siguiente manera:
var subdomain = window.location.host.split('.')[1] ? window.location.host.split('.')[0] : false;
Sí, la alerta (window.location.hostname) incluirá subdominios como 'www' y 'muestra'.
¿Qué hay de este fragmento. Podría ayudar:
var a = new String(window.location);
a = a.replace('http://','');
a = a.substring(0, a.indexOf('/'));
alert(a);
Esto hace el truco para mí:
var host = window.location.host
var subdomain = host.split('.’)[0]