새소식

반응형
WEB/JavaScript

[JavaScript] 현재 URL 정보를 가져오는 방법들

  • -
반응형

2023-06-14


사진: Unsplash 의 NEOM


1. 방법

 

현재 URL 정보를 가져오는 방법은 window.location 객체를 사용하는 것입니다. window.location 객체는 현재 페이지의 URL과 관련된 정보를 제공합니다. 아래의 속성을 사용하여 다양한 정보를 얻을 수 있습니다:

window.location.href: 전체 URL을 반환합니다.
window.location.protocol: 프로토콜 (예: "http:", "https:")을 반환합니다.
window.location.host: 호스트 이름과 포트를 반환합니다.
window.location.hostname: 호스트 이름을 반환합니다.
window.location.port: 포트 번호를 반환합니다.
window.location.pathname: 경로 부분을 반환합니다.
window.location.search: 쿼리 파라미터 부분을 반환합니다.
window.location.hash: 해시 부분을 반환합니다.

 

예를 들어, http://example.com/page?param1=value1#section1와 같은 URL이 있다면 다음과 같이 해당 정보에 접근할 수 있습니다:

 

console.log(window.location.href);      // "http://example.com/page?param1=value1#section1"
console.log(window.location.protocol);  // "http:"
console.log(window.location.host);      // "example.com"
console.log(window.location.hostname);  // "example.com"
console.log(window.location.port);      // ""
console.log(window.location.pathname);  // "/page"
console.log(window.location.search);    // "?param1=value1"
console.log(window.location.hash);      // "#section1"

메인 이미지 출처 : 사진: UnsplashNEOM  

반응형
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.