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?

¿Fue útil?

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í

Ubicación de la ventana

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]
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top