文字列のエスケープ・エンコード処理
文字列のエスケープ・エンコード処理を行うには、escape関数、encodeURI関数、encodeURIComponent関数のいずれかを使用します。
これらはエスケープしない文字列とエスケープシーケンスに違いがありますが、escape関数は非推奨とされているため、encodeURI関数かencodeURIComponent関数を使用します。
構文
var result = escape(str);
var result = encodeURI(str);
var result = encodeURIComponent(str);
| 引数名 | 型 | 説明 | |
|---|---|---|---|
| 第一引数 必須 |
str | string | エスケープ・エンコードする文字列 |
戻り値:escape
16進数のエスケープシーケンスでエンコーディングされた文字列を返します。
戻り値:encodeURI
UTF-8エンコーディングされた文字列を返します。
戻り値:encodeURIComponent
UTF-8エンコーディングされた文字列を返します。
エスケープしない文字列の一覧
| 関数名 | エスケープしない文字列 |
|---|---|
| escape | 英字、数字、-、_、. |
| encodeURI | 英字、数字、-、_、.、!、~、*、'、(、)、;、,、/、?、:、@、&、=、+、$、# |
| encodeURIComponent | 英字、数字、-、_、.、!、~、*、'、(、) |
サンプルコード
JavaScript
var str = 'abcdefg123456-_.!~*\'();,/?:@&=+$あいうえおテスト#';
var result1 = escape(str),
result2 = encodeURI(str),
result3 = encodeURIComponent(str);
alert(result1);
alert(result2);
alert(result3);