この文書は翻訳中です。他国語のままの部分などがあるのはその為です。
是非お気軽に MDN に登録して翻訳に参加し、私たちの手助けをして下さい!
概要
特定の文字の実体を、UTF-8 文字エンコーディングで表された 1 つ、2 つ、あるいは、3 つのエスケープシーケンスに置き換えることで、統一資源識別子 (Uniform Resource Identifier (URI)) の要素をエンコードします。
| コア・グローバル・メソッド | |
|---|---|
| 実装されたバージョン | JavaScript ? |
| ECMAScript エディション | ECMAScript ? |
構文
var encoded = encodeURIComponent(str);
引数
-
str - URI の要素
説明
encodeURIComponent は、次を除く全ての文字をエスケープします。: アルファベット、数字、- _ . ! ~ * ' ( )
ユーザ入力パラメータを、URI の一部としてサーバに渡す場合には【訳注: GETメソッド】、サーバに想定外のリクエストが渡らないように、encodeURIComponent で処理する必要があります。例えば、ユーザーがパラメータ comment の値として "Thyme &time=again" を入力するかもしれません。 このパラメータ 【訳注: キーと値の組】 を encodeURIComponent で処理しておかないと、サーバには comment=Thyme%20&time=again という表現が渡ってしまいます。 ここで、アンパサンド '&' と 等号 '=' は、新しいパラメータのキーと値を表すことに注意してください。 つまり、1つのパラメータ(キー comment とその値 "Thyme &time=again") を送信したつもりが、 実際には 2つのパラメータ(キー comment とその値 "Thyme "と 、そして もう一つのキー time とその値 "again")が送信されてしまいます【訳注: キーや値の文字列中の'&'をエンコード処理しておかないと、サーバは'&'を新しいパラメータの開始記号と解釈してしまう】。
For application/x-www-form-urlencoded (POST), per http://www.w3.org/TR/html401/interac...m-content-type, spaces are to be replaced by '+', so one may wish to follow a encodeURIComponent replacement with an additional replacement of "%20" with "+".
If one wishes to be more stringent in adhering to RFC 3986 (which reserves !, ', (, ), and *), even though these characters have no formalized URI delimiting uses, the following can be safely used:
function fixedEncodeURIComponent (str) {
return encodeURIComponent(str).replace(/[!'()]/g, escape).replace(/\*/g, "%2A");
}
Mozilla Developer Network