JavaScript는 문자열을 인코딩하기 위해 escape() 함수를 제공해 왔습니다. 하지만 escape() 함수는 현재 폐기(deprecated)된 상태이므로, 실제 개발에서는 encodeURI() 또는 encodeURIComponent()를 사용하는 것이 좋습니다.
문법
escape(string);
encodeURIComponent(str);
예제 1: escape() 함수 사용
다음 예제에서는 escape() 메서드를 사용하여 문자열 "Tutorix is the best e-learning platform!!!"을 인코딩하고, 그 결과를 화면에 출력합니다.
<html>
<body>
<script>
document.write(escape("Tutorix is the best e-learning platform!!!"));
</script>
</body>
</html>출력 결과
Tutorix%20is%20the%20best%20e-learning%20platform%21%21%21
출력 결과를 보면 공백은 %20, 느낌표(!)는 %21로 변환된 것을 확인할 수 있습니다.
예제 2: encodeURIComponent() 함수 사용
다음 예제에서는 encodeURIComponent() 메서드를 사용하여 동일한 문자열을 인코딩하고 그 결과를 출력합니다.
<html>
<body>
<script>
document.write(encodeURIComponent("Tutorix is the best e-learning platform!!!"));
</script>
</body>
</html>출력 결과
Tutorix%20is%20the%20best%20e-learning%20platform!!!
escape()와 encodeURIComponent()의 차이점
두 함수의 가장 큰 차이는 특수 문자 처리 방식입니다. escape()는 느낌표(!)와 같은 ASCII 특수 문자까지 인코딩하지만, encodeURIComponent()는 알파벳, 숫자, 그리고 일부 예약되지 않은 문자(- _ . ! ~ * ' ( ))는 인코딩하지 않고 그대로 유지합니다.
또한 encodeURIComponent()는 URI의 구성 요소(쿼리 파라미터 값 등)를 인코딩할 때 적합하며, 전체 URL을 인코딩할 때는 encodeURI()를 사용하는 것이 올바른 방법입니다.