Script
도메인 정보 가져오기
자바초보자
2016. 3. 22. 15:15
728x90
Q>
현재 페이지 주소가 다음과 같을 떄
https://localhost:8181/ContactUs-1.0/contact?lang=it&report_type=consumer
url에서 프로토콜, 도메인, 포트 번호를 얻고 싶습니다. (https://localhost:8181)
자바스크립트로 어떻게 할 수 있을까요?
A>
프로토콜 : location.protocol
도메인 : location.host
포트 : location.port
도메인 + 포트 : location.host
입니다. 따라서,
var full = location.protocol+‘//’+location.hostname+(location.port ? ‘:’+location.port: ”);
로 하면 원하는 url을 얻으실 수 있습니다.
A>
1. 먼저 현재 주소를 알아냅니다.
var url = window.location.href
2. 경로는 “/” 로 구분되니 이를 구분자로 쪼개줍니다.
var arr = url.split(“/”);
3. 프로토콜과 도메인 주소가 담긴 인덱스를 참조하면 됩니다.
var result = arr[0] + “//” + arr[2]
참고로 arr[1]은 빈 문자가 들어가게 됩니다. 또한 “/” 로 split() 했을 경우 프로토콜만 별도로 얻어지지는 않습니다. arr[2]에 담긴 도메인주소를 가지고 한 번 더 작업이 필요합니다.
728x90