JavaScript에서 URL을 디코딩하려면 decodeURI() 메서드를 사용하면 됩니다. 이 메서드는 encodeURI() 함수로 인코딩된 URI를 원래의 읽기 가능한 형태로 되돌려 주며, 공백(%20)처럼 퍼센트 인코딩으로 변환된 문자들을 다시 복원합니다.
예제
아래 예제에서는 먼저 encodeURI()로 URI를 인코딩한 뒤, decodeURI()로 다시 디코딩하여 두 결과를 화면에 출력합니다. 버튼을 클릭하면 결과를 바로 확인할 수 있습니다.
<!DOCTYPE html>
<html>
<body>
<button onclick="display()">Check</button>
<p id="demo"></p>
<script>
function display() {
var uri = "welcome msg.jsp?name=amit&sub=programming";
// 먼저 인코딩
var encode = encodeURI(uri);
var decode = decodeURI(encode);
var result = "Encode= " + encode + "<br>" + "Decode= " + decode;
document.getElementById("demo").innerHTML = result;
}
</script>
</body>
</html>실행 결과
버튼을 클릭하면 다음과 같은 결과가 표시됩니다.
- Encode: welcome%20msg.jsp?name=amit&sub=programming — 공백이
%20으로 변환됩니다. - Decode: welcome msg.jsp?name=amit&sub=programming — 원래 문자열로 복원됩니다.
참고 사항
decodeURI()는 encodeURI()로 인코딩된 전체 URI를 디코딩할 때 사용합니다. 반면 encodeURIComponent()로 인코딩한 문자열이라면 반드시 decodeURIComponent()를 사용해야 올바르게 복원됩니다. 특히 쿼리 문자열의 개별 파라미터 값을 다룰 때는 encodeURIComponent() / decodeURIComponent() 조합이 더 안전하고 권장되는 방식입니다.