JavaScript

URLSearchParams로 Url Query String 가져오기

citron031 2023. 10. 3. 22:33

바닐라 자바스크립트로 URL의 쿼리 스트링을 가져오는 방법을 알아보았다.

React-Router-Dom이나 Next에서는 해당 기능에 대한 훅이 존재하지만, 바닐라 자바스크립트로도 간단히 이를 구현할 수 있다.

 

우선, window.location.search으로 URL에서 쿼리만 가져올 수 있다.

console.log(window.location.search);
// '?search=hihihi'

 

그리고 해당 String을 URLSearchParams의 인자로 전달하면, key-value의 형태로 값을 구조화할 수 있다.

const searchParams = new URLSearchParams(window.location.search);

for (const [key, value] of searchParams) {
    console.log(key, value); // search hihihi
}

 

URLSearchParams의 인자로 반드시 쿼리 스트링만 들어갈 수 있는 것은 아니고, 일반 URL이나 심지어 객체도 인자로 사용될 수 있다.

 

🌧️ 참고자료

https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams

 

URLSearchParams - Web APIs | MDN

The URLSearchParams interface defines utility methods to work with the query string of a URL.

developer.mozilla.org