Computer >> 컴퓨터 >  >> 프로그래밍 >> JavaScript

JavaScript에서 문자열을 인코딩하고 디코딩하는 방법

문자열 인코딩과 디코딩의 기본

JavaScript에서 문자열을 인코딩하려면 encodeURIComponent() 또는 encodeURI()를 사용하고, 디코딩하려면 decodeURIComponent() 또는 decodeURI()를 사용합니다. 과거에는 escape() 함수로 문자열을 인코딩했지만, 이 함수는 이미 폐기(deprecated)된 상태이므로 현재는 encodeURI()를 사용하는 것이 표준입니다.


두 함수의 차이도 알아두면 좋습니다. encodeURI()는 URL 전체를 인코딩할 때 사용하며, ':', '/', '?', '#'처럼 URL 구조에 필수적인 특수문자는 그대로 유지합니다. 반면 encodeURIComponent()는 쿼리 파라미터 값처럼 URL의 일부 구성 요소를 인코딩할 때 사용하며, 대부분의 특수문자까지 모두 변환합니다.

구문

인코딩

encodeURIComponent(string);

디코딩

decodeURIComponent(string);

예제

다음 예제에서는 먼저 하나의 문자열을 준비한 뒤, encodeURI()로 인코딩하고 이어서 decodeURI()로 다시 디코딩합니다. 마지막으로 인코딩된 결과와 디코딩된 결과를 함께 화면에 출력합니다.

<html>
<body>
<p id = "encoding"></p>
<script>
   var str = "Tutorix is the best e-learning platform";
   var enc = encodeURI(str);
   var dec = decodeURI(enc);
   var res = "After encoding: " + enc + "
   </br>" + "After Decoding: " + dec;
   document.getElementById("encoding").innerHTML = res;
</script>
</body>
</html>

실행 결과

After encoding: Tutorix%20is%20the%20best%20e-learning%20platform
After Decoding: Tutorix is the best e-learning platform

출력 결과에서 확인할 수 있듯이, 공백 문자는 인코딩 과정에서 %20으로 변환되며, 디코딩을 거치면 원래의 공백으로 복원됩니다. 이러한 인코딩 방식은 URL에 한글이나 특수문자를 포함하여 데이터를 전송해야 할 때 특히 유용하게 활용됩니다.