웹 브라우저에서 JavaScript를 사용할 때, window.location.search 속성은, 현재 페이지 의 쿼리 스트링에 접근하여 현재 페이지 URL의 쿼리 스트링 부분을 가져옵니다.
이는 '?' 문자로 시작하여 URL의 파라미터를 포함하는 문자열입니다. 이 문자열을 사용하여 페이지의 동작을 조절하거나, 특정 파라미터에 따라 다른 내용을 표시할 수 있습니다.
현재 URL 창에 http://4ok.kr/?userId=1234&theme=dark 이라면, const urlParams = window.location.search;console.log(urlParams) // ?userId=1234&theme=dark
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Query String Example</title>
</head>
<body>
<script>
// 현재 페이지의 URL에서 쿼리 스트링을 가져옵니다.
const queryString = window.location.search;
// URLSearchParams 객체를 사용하여 쿼리 파라미터를 파싱합니다.
const queryParams = new URLSearchParams(queryString);
// 개별 쿼리 파라미터를 가져옵니다.
const userId = queryParams.get('userId');
const theme = queryParams.get('theme');
console.log('User ID:', userId); // 출력: 1234
console.log('Theme:', theme); // 출력: dark
// 페이지의 동작을 조절하는 로직
if (theme === 'dark') {
document.body.style.backgroundColor = '#333';
document.body.style.color = '#fff';
} else {
document.body.style.backgroundColor = '#fff';
document.body.style.color = '#000';
}
</script>
</body>
</html>
Array.from() 활용 (0) | 2024.04.30 |
---|---|
UUID (0) | 2024.04.26 |
URLSearchParams, qs - 쿼리 스트링을 다루는 API (0) | 2024.04.25 |
firebase hosting + vite.js (0) | 2024.04.17 |
Vite.js 에서 환경변수 사용 .env (1) | 2024.04.17 |