문자열 인코딩 문제

✒️ 2025-04-29 20:25 내용 수정


문제 상황

http://localhost/html/search.html?query=동물
// 'query=동물'이라고 생각했으나 실제로는 인코딩된 문자열
const query = window.location.search.split('=')[1]; // 주소창이 ?query=키워드 형식

//... 중략
const str = "동물 곤충 사람";
const isContained = str.includes(query); // false

원인 분석

http://localhost/html/search.html?query=%EB%8F%99%EB%AC%BC
console.log(window.location);

window_location_encoding 1.png


해결 방법

// URLSearchParams 객체를 window.location.search로 생성
const params = new URLSearchParams(window.location.search);

// param을 query string으로 쓸 수 있는 문자열 형식으로 반환
console.log(params.toString())

// params의 모든 키(key)를 콘솔로 출력
for (const key of params.keys()) {
    console.log(key);
}

// params의 모든 값(value)을 출력
for (const value of params.values()) {
    console.log(value);
}

window_location_encoding 2.png

const query = decodeURIComponent(params.get("query") || "");

// ... 중략

const str = "동물 곤충 사람";
const isContained = str.includes(query); // true

기타 비교 조건

참고 자료 : mdn web docs String.incudes(), 정규 표현식

1. 공백 차이

const query = "서울역";
const str = "서울 역에서 만난 사람들";

console.log(videoTitle.includes(searchQuery)); // false
const query = "서울역";
const str = "서울 역에서 만난 사람들";

// 공백 제거
const normalizedQuery = searchQuery.replace(/\s+/g, '');
const normalizedTitle = videoTitle.replace(/\s+/g, '');

console.log(normalizedTitle.includes(normalizedQuery)); // true

2. 대소문자 구분

let query = "test";
let str = "TEST";

console.log(str.includes(query)); // false

// 모두 소문자로 통일
query = query.toLowerCase();
str = str.toLowerCase();

console.log(str.includes(query)); // true