문제

다음과 같은 호스트 이름이있는 경우 http://sample.example.com 그리고 JavaScript에서 나는한다 window.location.hostname, "example.com"또는 "sample.example.com"을받을 수 있습니까?

그렇지 않다면 어떻게 sample.example.com을 얻을 수 있습니까?

도움이 되었습니까?

해결책

예, window.location.hostname 하위 도메인도 줄 것입니다. 이것이 작동하지 않거나 다른 브라우저에서 지원하지 않는 경우 쉽게 구문 분석 할 수 있습니다.

// window.location.href == "http://sample.somedomain.com/somedir/somepage.html"
var domain = /:\/\/([^\/]+)/.exec(window.location.href)[1];

다른 팁

우선, 그것은입니다 window.location, 아니다 document.location (document.location 일부 브라우저에서 작동하지만 표준은 아닙니다)

그리고 네, location.hostname ~ 할 것이다 하위 도메인을 포함하여 전체 도메인 이름을 반환하십시오

여기에서 자세히 알아보십시오

창 위치

다음과 같이 수행 할 수 있습니다.

var subdomain =  window.location.host.split('.')[1] ? window.location.host.split('.')[0] : false;

예 Alert (window.location.hostname)에는 'www'및 'sample'과 같은 하위 도메인이 포함됩니다.

이 스 니펫은 어떻습니까. 도움이 될 수 있습니다 :

var a = new String(window.location);
a = a.replace('http://','');
a = a.substring(0, a.indexOf('/'));
alert(a);

이것은 나에게 트릭을합니다.

var host = window.location.host
var subdomain = host.split('.’)[0]
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top