디코딩 정리

인코딩된 데이터를 다시 원래대로 되돌리는 게 디코딩이다.

어디서 필요한가

URL에서

%EC%95%88 → 안
%20 → 띄어쓰기

사람이 읽을 수 있게 복원해야 한다.

파일 받을 때

base64 → 이미지
UTF-8 → 한글 텍스트

코드 예시

URL 디코딩

const encoded = '%EA%B0%95%EC%9D%98';
const decoded = decodeURIComponent(encoded);
console.log(decoded); // '강의'
 
// 실제 검색 URL 파싱
const url = 'https://search?q=%EA%B2%80%EC%83%89%EC%96%B4';
const searchTerm = decodeURIComponent(url.split('q=')[1]);
console.log(searchTerm); // '검색어'

Base64 이미지 복원

const base64 = 'data:image/jpeg;base64,/9j/4AAQSkZJRg...';
const img = new Image();
img.src = base64; // 자동으로 이미지로 변환됨

자주 하는 실수: 디코딩 두 번 하기

// 이러면 에러 남
const text = decodeURIComponent(decodeURIComponent(encoded));

이미 디코딩된 문자열을 한 번 더 디코딩하면 예외가 발생한다.

디코딩이 필요한 상황

  • 서버에서 API 응답 받을 때
  • URL 쿼리 파라미터 파싱 (검색어, 한글 파일명)
  • 파일 다운로드
  • 웹소켓·채팅 (이모지, 특수문자)

참고자료

MDN 공식문서 - decodeURIComponent