JavaScript / location 객체로 URL·도메인·경로 가져오기

window.location은 현재 문서의 URL을 나타내는 Location 객체입니다. 전체 주소는 location.href, 도메인 이름은 location.hostname, 경로는 location.pathname으로 읽습니다. 주소를 나누어 분석만 할 때는 new URL(location.href)도 편리합니다.

현재 주소에서 자주 쓰는 부분

예를 들어 주소가 https://example.com:8080/path/page.html?lang=ko#part라고 가정하면 각 속성은 아래와 같습니다. host에는 도메인과 포트가 함께 들어가고 hostname에는 포트가 들어가지 않습니다.

속성 예시 값 뜻
href https://example.com:8080/path/page.html?lang=ko#part 전체 URL
origin https://example.com:8080 프로토콜·호스트·포트
protocol https: 끝에 콜론 포함
host example.com:8080 호스트명과 포트
hostname example.com 호스트명
pathname /path/page.html 쿼리·해시 제외 경로
search ?lang=ko 물음표 포함 쿼리
hash #part 해시 기호 포함 조각

포트가 기본 포트이거나 지정되지 않았다면 port는 빈 문자열이고 host에도 별도 포트가 나타나지 않습니다. 화면에 표시된 주소 문자열을 직접 잘라서 해석하기보다 속성을 읽으면 경계와 인코딩을 잘못 계산할 가능성이 줄어듭니다. MDN의 Location 인터페이스 문서에서 전체 속성을 확인할 수 있습니다.

Location과 URL 객체를 구분하기

window.location은 지금 열려 있는 페이지에 연결됩니다. location.href를 다른 주소로 설정하면 페이지가 이동합니다. 반면 new URL(address)은 주소를 분석·구성할 새 객체를 만들 뿐 현재 페이지를 이동시키지 않습니다. 테스트용 주소를 안전하게 다루려면 URL을 사용하세요.

const current = window.location;
console.log(current.href);     // 지금 문서의 전체 주소
console.log(current.pathname); // 지금 문서의 경로

const sample = new URL('https://example.com:8080/path/page.html?lang=ko#part');
console.log(sample.host);      // 'example.com:8080'
console.log(sample.hostname);  // 'example.com'
console.log(sample.searchParams.get('lang')); // 'ko'

쿼리 문자열은 search에 물음표까지 포함되므로 매개변수 하나를 읽으려면 URL.searchParams.get()을 쓰는 편이 쉽습니다. 같은 이름의 매개변수가 여러 개라면 get()은 첫 값만 반환하므로 전체가 필요할 때는 getAll()을 선택하세요. MDN의 URL 인터페이스 문서와 URL.searchParams 문서를 참고할 수 있습니다.

전체 예제: 현재 페이지와 입력한 주소 비교

아래 코드를 UTF-8로 location-example.html에 저장해 브라우저에서 엽니다. 기본 예제 주소를 ‘URL 분석’으로 살펴보거나 ‘현재 페이지 주소’를 누르면 실제 열린 문서의 주소를 분석합니다. 이 예제는 주소를 읽기만 하며 페이지를 이동시키지 않습니다.

<!doctype html>
<html lang="ko">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>URL 부분 확인 실습</title>
</head>
<body>
<label for="address">분석할 절대 URL</label>
<input id="address" type="url" size="60" value="https://example.com:8080/path/page.html?lang=ko#part">
<button id="parse" type="button">URL 분석</button>
<button id="current" type="button">현재 페이지 주소</button>
<button id="reset" type="button">처음으로</button>
<pre id="output" aria-live="polite"></pre>
<script>
const address = document.querySelector('#address');
const output = document.querySelector('#output');

function show(value) {
  try {
    const url = new URL(value);
    output.textContent = [
      `href: ${url.href}`,
      `origin: ${url.origin}`,
      `protocol: ${url.protocol}`,
      `host: ${url.host}`,
      `hostname: ${url.hostname}`,
      `port: ${url.port || '(없음)'}`,
      `pathname: ${url.pathname}`,
      `search: ${url.search || '(없음)'}`,
      `hash: ${url.hash || '(없음)'}`,
      `lang 매개변수: ${url.searchParams.get('lang') ?? '(없음)'}`,
    ].join('\n');
  } catch (error) {
    output.textContent = '유효한 절대 URL을 입력하세요.';
  }
}

document.querySelector('#parse').addEventListener('click', () => show(address.value));
document.querySelector('#current').addEventListener('click', () => {
  address.value = window.location.href;
  show(address.value);
});
document.querySelector('#reset').addEventListener('click', () => {
  address.value = 'https://example.com:8080/path/page.html?lang=ko#part';
  show(address.value);
});
show(address.value);
</script>
</body>
</html>

기본 주소에서 host는 example.com:8080, hostname은 example.com, pathname은 /path/page.html, lang 매개변수는 ko입니다. 형식이 잘못된 절대 URL을 입력하면 안내가 나옵니다. ‘처음으로’를 누르면 예제 주소가 돌아옵니다. 파일로 연 경우 현재 주소는 file: URL이므로 웹 서버에서 연 주소와 각 항목이 다를 수 있습니다.

주소를 변경할 때의 동작

페이지 이동이 목적이라면 location.assign(url) 또는 location.href = url을 사용할 수 있습니다. location.replace(url)는 현재 페이지를 방문 기록의 해당 항목에서 대체하므로 뒤로 가기 동작이 달라집니다. 이동 여부와 방문 기록 처리 방식이 사용자 흐름에 맞는지 판단하고 사용하세요.

외부에서 받은 주소로 이동시키는 경우에는 예상한 사이트와 프로토콜인지 검증해야 합니다. 입력 URL을 읽는 예제와 실제 이동 코드를 혼동하지 마세요. MDN의 Location.href 문서에는 값 변경에 따른 이동이 설명되어 있습니다.