This article is in need of an editorial review.
概要
特定の文字の実体を、UTF-8 文字エンコーディングで表された 1つ、2つ、あるいは、3つのエスケープシーケンスに置き換えることで、URI (Uniform Resource Identifier) をエンコードします。(サロゲートペアで構成される文字のみ4つのエスケープシーケンスになります)。
構文
encodeURIComponent(str);
引数
str- URI の文字列
説明
encodeURIComponent は次を除く全ての文字をエスケープします。: 英数字, - _ . ! ~ * ' ( )
上位・下位のペアでないサロゲート文字をエンコードしようとした場合 URIError が発生します。
例
// 上位・下位の正しいペア
console.log(encodeURIComponent('\uD800\uDFFF'));
// 上位のみであり "URIError: malformed URI sequence" が発生
console.log(encodeURIComponent('\uD800'));
// 下位のみであり "URIError: malformed URI sequence" が発生
console.log(encodeURIComponent('\uDFFF'));
予想外のサーバへのリクエストを避けるために、URIの一部として送られるであろうユーザーの入力値があるならば、encodeURIComponentを呼び出すべきです。たとえば、ユーザーはcomment変数に"Thyme &time=again"とタイプできます。この変数にencodeURIComponentを使用しないと、comment=Thyme%20&time=againが与えられます。アンパサンドと=記号は新しいキー/バリューペアであることに注意してください。そのため、"Thyme &time=again"と等しいcommentキーがポストされる代わりに、1つは"Thyme "と等しく、もう1つ(time) はagainと等しい二つのキーがポストされます。
application/x-www-form-urlencoded (POST) のために、スペースが'+'に置き換えられるだけでなく、"%20"を+に追加変換したい人もいるでしょう。
RFC 3986 (これは!、 '、(、)と*を予約します)に関連してより厳格にするために、これらの文字は正式なURI区切りの用途がないですが、以下の例は安全に使用できます。
function fixedEncodeURIComponent (str) {
return encodeURIComponent(str).replace(/[!'()]/g, escape).replace(/\*/g, "%2A");
}
例
次の例は、UTF-8 Content-DispositionとLink のサーバーレスポンスヘッダーパラメーターで求められている特別なエンコーディングを提供します。(例 UTF-8 filenames):
var fileName = 'my file(2).txt';
var header = "Content-Disposition: attachment; filename*=UTF-8''" + encodeRFC5987ValueChars(fileName);
console.log(header);
// logs "Content-Disposition: attachment; filename*=UTF-8''my%20file%282%29.txt"
function encodeRFC5987ValueChars (str) {
return encodeURIComponent(str).
// Note that although RFC3986 reserves "!", RFC5987 does not,
// so we do not need to escape it
replace(/['()]/g, escape). // i.e., %27 %28 %29
replace(/\*/g, '%2A').
// 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, unescape);
}
仕様
| Specification | Status | Comment |
|---|---|---|
| ECMAScript 3rd Edition. | Standard | Initial definition. |
| ECMAScript 5.1 (ECMA-262) The definition of 'encodeURIComponent' in that specification. |
Standard | |
| ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'encodeURIComponent' in that specification. |
Standard |
ブラウザ実装状況
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| Basic support | (有) | (有) | (有) | (有) | (有) |
| Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|---|
| Basic support | (有) | (有) | (有) | (有) | (有) | (有) |
関連項目