encodeURI, encodeURIComponent 모두 브라우저/node 환경 불문하고 사용할 수 있는 자바스크립트 빌트인 함수이다. URL은 표준 ASCII 문자들로만 구성되어야 하고, 다른 특수 문자들은 모두 인코딩 처리되어야한다. 이를 위해 encodeURI와 encodeURIComponent가 사용된다 이 함수들의 역할은 인자로 받은 문자열의 특정문자들을 UTF-8 형식으로 인코딩하는 것이다. 자꾸 헷갈려서 둘의 차이점이 뭔지 알아봤다.
encodeURI의 역할은 완전한 URL를 인코딩하는 것이다. A-Z a-z 0-9 ; , / ? : @ & = + $ - _ . ! ~ * ' ( ) # 문자들을 제외한 모든 문자를 이스케이프한다.
const encoded = encodeURI('https://blog.mskwon.click/path to a great post');
console.log(encoded); // 'https://domain.com/path%20to%20a%20great'
encodeURIComponent의 경우에는 쿼리스트링과 같이 URI의 특정 부분을 인코딩할때 사용하는 것이 목적이다.
const encoded = `https://blog.mskwon.click/?search=\${encodeURIComponent('encode & decode param')}`;
console.log(encoded); // 'http://domain.com/?search=encode%20%26%20decode%20param'\
그리고 그 목적에 맞게, encodeURI는 건드리지 않는 11가지 문자들(;,/?:@&=+$#)도 인코딩한다. 특히 &, +, = 세 문자의 경우 HTTP GET과 POST 요청에서 특별한 문자로 취급하는 문자들이기 때문에, 이 문자들을 인코딩 하지 않는 encodeURI 단독으로는 HTTP GET / POST 요청을 구성할 수 없다. 따라서, 필요한 부분에 encodeURIComponent를 사용해줘야한다.
const encoded = `https://blog.mskwon.click/?search=\${encodeURIComponent('encode & decode param')}`;
console.log(encoded); // 'http://domain.com/?search=encode%20%26%20decode%20param'