encodeURIComponent() 전역 함수
encodeURIComponent() 전역 함수
encodeURIComponent()는 특정 문자들의 각 인스턴스를 그 문자의 UTF-8 인코딩을 나타내는 하나, 둘, 셋 또는 넷의 이스케이프 시퀀스로 대체해 URI를 인코딩하는 전역 함수입니다. encodeURI()와 비교해 더 많은 문자(URI 구문의 일부인 문자 포함)를 인코딩합니다.
본문
개요
encodeURIComponent() 함수는 UTF-8 인코딩을 나타내는 이스케이프 시퀀스로 문자를 대체해 uriComponent를 인코딩한 새 문자열을 반환합니다. URI의 구성 요소(경로·쿼리 문자열·프래그먼트 등)를 안전하게 인코딩할 때 사용됩니다.
기본적인 사용 예는 다음과 같습니다.
// Encodes characters such as ?,=,/,&,:
console.log(`?x=${encodeURIComponent("test?")}`);
// Expected output: "?x=test%3F"
console.log(`?x=${encodeURIComponent("шеллы")}`);
// Expected output: "?x=%D1%88%D0%B5%D0%BB%D0%BB%D1%8B"
구문(Syntax)
encodeURIComponent(uriComponent)
매개변수
- uriComponent — URI 구성 요소(경로, 쿼리 문자열, 프래그먼트 등)로 인코딩할 문자열입니다. 다른 값은 문자열로 변환됩니다.
반환값 — 제공된 uriComponent를 URI 구성 요소로 인코딩한 새 문자열입니다.
예외(Exceptions)
- URIError —
uriComponent에 고립 서러게이트(lone surrogate)가 포함된 경우 발생합니다.
설명(Description)
encodeURIComponent()는 전역 객체의 함수 프로퍼티입니다.
encodeURIComponent()는 encodeURI()에서 설명한 것과 동일한 인코딩 알고리즘을 사용합니다. 다음 문자를 제외한 모든 문자를 이스케이프합니다.
A–Z a–z 0–9 - _ . ! ~ * ' ( )
encodeURI()와 비교해 encodeURIComponent()는 더 큰 문자 집합을 이스케이프합니다. 서버로 보내는 폼의 사용자 입력 필드에 encodeURIComponent()를 사용하십시오 — 이는 데이터 입력 중 실수로 생성될 수 있는 문자 참조(character references)나 인코딩/디코딩이 필요한 다른 문자를 위한 & 기호를 인코딩합니다. 예를 들어 사용자가 Jack & Jill이라고 쓰면, encodeURIComponent()가 없으면 앰퍼샌드가 서버에서 새 필드의 시작으로 해석되어 데이터 무결성을 위협할 수 있습니다.
application/x-www-form-urlencoded의 경우 공백은 +로 대체되어야 하므로, encodeURIComponent() 대체 이후 %20을 +로 대체하는 추가 대체를 수행할 수 있습니다.
예제
Content-Disposition 및 Link 헤더용 인코딩 — 다음 예제는 UTF-8 Content-Disposition 및 Link 서버 응답 헤더 매개변수(예: UTF-8 파일 이름)에 필요한 특수 인코딩을 제공합니다.
const fileName = "my file(2).txt";
const header = `Content-Disposition: attachment; filename*=UTF-8''${encodeRFC5987ValueChars(
fileName,
)}`;
console.log(header);
// "Content-Disposition: attachment; filename*=UTF-8''my%20file%282%29.txt"
function encodeRFC5987ValueChars(str) {
return (
encodeURIComponent(str)
// The following creates the sequences %27 %28 %29 %2A (Note that
// the valid encoding of "*" is %2A, which necessitates calling
// toUpperCase() to properly encode). Although RFC3986 reserves "!",
// RFC5987 does not, so we do not need to escape it.
.replace(
/['()*]/g,
(c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`,
)
// The following are not required for percent-encoding per RFC5987,
// so we can allow for a little better readability over the wire: |`^
.replace(/%(7C|60|5E)/g, (str, hex) =>
String.fromCharCode(parseInt(hex, 16)),
)
);
}
RFC3986용 인코딩 — 더 최신의 RFC3986은 !, ', (, ), *를 예약합니다. 이 문자들은 공식화된 URI 구분 용도가 없음에도 불구하고 그렇습니다. 다음 함수는 RFC3986 호환 URL 구성 요소 형식으로 문자열을 인코딩합니다. 또한 IPv6 URI 구문의 일부인 [와 ]도 인코딩합니다. RFC3986 호환 encodeURI 구현은 이들을 이스케이프하지 않아야 합니다.
function encodeRFC3986URIComponent(str) {
return encodeURIComponent(str).replace(
/[!'()*]/g,
(c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`,
);
}
고립 서러게이트 인코딩은 예외를 던짐 — 높은-낮은 쌍(high-low pair)의 일부가 아닌 서러게이트를 인코딩하려고 하면 URIError가 발생합니다.
// High-low pair OK
encodeURIComponent("\uD800\uDFFF"); // "%F0%90%8F%BF"
// Lone high-surrogate code unit throws "URIError: malformed URI sequence"
encodeURIComponent("\uD800");
// Lone high-surrogate code unit throws "URIError: malformed URI sequence"
encodeURIComponent("\uDFFF");
고립 서러게이트를 유니코드 대체 문자(U+FFFD)로 바꾸는 String.prototype.toWellFormed()를 사용해 이 오류를 피할 수 있습니다. 또한 String.prototype.isWellFormed()를 사용해 encodeURIComponent()에 전달하기 전에 문자열에 고립 서러게이트가 있는지 확인할 수 있습니다.