javascript

encodeURI, encodeURIComponent, escape 함수 차이점; 자바스크립트

jeeyong 2008. 11. 17. 10:38
자바스크립트(JavaScript)에서는 다음의 함수들로, HTML 페이지 주소를 인코딩/디코딩합니다.

encodeURI() / decodeURI()
최소한의 문자만 인코딩합니다.
; / ? : @ & = + $ , - _ . ! ~ * ' ( ) #
이런 문자는 인코딩하지 않습니다.
http:// ... 등은 그대로 나옵니다.


encodeURIComponent() / decodeURIComponent()
알파벳과 숫자 Alphanumeric Characters 외의, 대부분의 문자를 모두 인코딩합니다.
http:// ... 가 http%3A%2F%2F 로 됩니다.



escape() / unescape()
예전부터 있던 오래된 함수입니다. encodeURI() 와 encodeURIComponent() 의 중간 정도의 범위로 문자를 인코딩합니다.


encodeURI, encodeURIComponent, escape 함수 사용 예제

<html>

<body>

<script type="text/javascript">
  var s;

  s = encodeURI('http://www.google.co.kr/소 설.html');
  document.write('<p>' + s + '<p>');
  // 출력 결과: http://www.google.co.kr/%EC%86%8C%20%EC%84%A4.html


  s = encodeURIComponent('http://www.google.co.kr/소 설.html');
  document.write('<p>' + s + '<p>');
  // 출력 결과: http%3A%2F%2Fwww.google.co.kr%2F%EC%86%8C%20%EC%84%A4.html


  s = escape('http://www.google.co.kr/소 설.html');
  document.write('<p>' + s + '<p>');
  // 출력 결과: http%3A//www.google.co.kr/%uC18C%20%uC124.html
</script>

</body>
</html>


어떤 함수든 "공백 문자" 즉 스페이스는 %20 으로 치환합니다. 그러나 주소의 공백은 없어야 합니다.


출처 : http://mwultong.blogspot.com/2006/10/encodeuri-encodeuricomponent-escape.html