JavaScript/JS: 문법 정리
[JS] 자바스크립트로 현재 주소값을 얻는 window.location.pathname과 window.location.href 비교
데브마우스
2024. 8. 27. 23:20
자바스크립트로 현재 주소의 URL을 얻기 위해서 자바스크립트 함수를 찾아보다가 window.location.pathname(이하 pathname)과 window.location.href(이하 href)를 알게 되었습니다.
하지만 두 함수의 반환 값은 다릅니다.
pathname
pathname은 현재 URL의 경로를 출력합니다.
http://www.devmoue.tistory.com/post/my-first-post
이런 URL이 있다면 /post/my-first-post를 출력합니다.
만약 ?나 #이 URL에 있어도 출력되지 않습니다.
https://devmouse.tistory.com/?search=javascript 혹은 https://devmouse.tistory.com/post/my-fisrt-post#comment1
이런 경우에도 ?를 포함하여 뒤에 출력되는 문자열이나 #를 포함하여 뒤에 출력되는 문자열은 출력되지 않습니다.
href
href는 현재 전체 URL을 출력합니다.
https://www.devmouest.tistory.com/post/my-fisrt-post가 있다면 이 URL 전체 그대로 출력합니다.그러니 당연히 pathname과 반대로 ?나 #뒤의 문자열도 함께 출력합니다.