JavaScript/공부공부
[JS] URL 객체
phyho
2025. 7. 15. 11:34
const u = new URL("https://test.co.kr:8000/path?query=value");
u.protocol // "https:"
u.hostname // "test.co.kr"
u.port // "8000"
u.host // "test.co.kr:8000"
u.origin // "https://test.co.kr:8000"
u.pathname // "/path"
u.search // "?query=value"
url형태의 문자열을 넣으면 자동으로 url 구성 요소들 분리 가능.
문자열 정규식보다 간편하고 안전하다.
로컬/배포 환경 차이로 url 구성이 달라지는 경우,
URL 객체를 활용해서 쉽게 비교.
const normalize = (url) => {
const u = new URL(url);
return `${u.protocol}//${u.hostname}`;
};
if (normalize(evenURL) !== normalize(baseURL)) return;