자바스크립트 encodeURI encodeURIComponent 차이 | URL 한글 인코딩 디코딩 방법과 예시

남양주개발자

·

2021. 10. 21. 07:51

728x90
반응형

자바스크립트 URL 한글 인코딩 디코딩 방법과 예시

자바스크립트에서 인코딩 처리를 할 때 자주 사용하는 encodeURI, encodeURIComponent 함수가 있는데요. 똑같은 문자열 인코딩 처리를 하는 것처럼 보이지만 문자열 인코딩 처리 방식이 조금 다릅니다. 상황에 따라서 제대로 활용하기 위해 이번 포스팅에서 해당 구문을 정리해보도록 하겠습니다.

encodeURI / decodeURI

encodeURI() 함수는 URI에서 특별한 뜻을 가진 문자(예약 문자)는 인코딩 하지 않습니다.

이스케이프 하지 않는 문자: 
A-Z a-z 0-9 ; , / ? : @ & = + $ - _ . ! ~ * ' ( ) #
예시)
// http://webruden.tistory.com/path/to/file.php?foo=123&bar=this has spaces

encodeURI('http://webruden.tistory.com/path/to/file.php?foo=123&bar=this has spaces');

// 결과
"http://webruden.tistory.com/path/to/file.php?foo=123&bar=this%2520has%2520spaces"

encodeURIComponent / decodeURIComponent

encodeURIComponent() 함수는 URI의 특정한 문자를 UTF-8로 인코딩해 하나, 둘, 셋, 혹은 네 개의 연속된 이스케이프 문자로 나타냅니다.  encodeURIComponent()는 다음 문자를 제외한 문자를 이스케이프 합니다.

이스케이프 하지 않는 문자: 
A-Z a-z 0-9 - _ . ! ~ * ' ( )
예시)
// http://webruden.tistory.com/path/to/file.php?foo=123&bar=this has spaces

encodeURIComponent("http://webruden.tistory.com/path/to/file.php?foo=123&bar=this has spaces")

// 결과
"http%3A%2F%2Fwebruden.tistory.com%2Fpath%2Fto%2Ffile.php%3Ffoo%3D123%26bar%3Dthis%20has%20spaces"

encodeURIComponent()와 encodeURI()의 차이

encodeURIComponent()와 encodeURI()의 차이는 아래와 같습니다.

const set1 = ";,/?:@&=+$";  // Reserved Characters
const set2 = "-_.!~*'()";   // Unescaped Characters
const set3 = "#";           // Number Sign
const set4 = "ABC abc 123"; // Alphanumeric Characters + Space

console.log(encodeURI(set1)); // ;,/?:@&=+$
console.log(encodeURI(set2)); // -_.!~*'()
console.log(encodeURI(set3)); // #
console.log(encodeURI(set4)); // ABC%20abc%20123 (the space gets encoded as %20)

console.log(encodeURIComponent(set1)); // %3B%2C%2F%3F%3A%40%26%3D%2B%24
console.log(encodeURIComponent(set2)); // -_.!~*'()
console.log(encodeURIComponent(set3)); // %23
console.log(encodeURIComponent(set4)); // ABC%20abc%20123 (the space gets encoded as %20)

정리

URI에서 특별한 의미를 가진 예약 문자는 인코딩하지 않고 처리하고 싶다면 encodeURI를 사용하면 되고, 전체 문자열을 모두 인코딩하고 싶다면 encodeURIComponent를 활용하면 됩니다.

728x90
반응형
그리드형

💖 저자에게 암호화폐로 후원하기 💖

아이콘을 클릭하면 지갑 주소가자동으로 복사됩니다