URIエンコード(URLエンコード)

 

URIエンコードに関連する RFC 文書には次のようなものがあります(いずれも日本語訳です)。

本稿では RFC 2396 を参照して「記号文字」のURIエンコードがどのようにあるべきかを確認します。 そして、これに対応する形で JavaScript の3つの関数(escape, encodeURI, encodeURIComponent) によるエンコード結果を表にまとめます。

RFC 2396 とエンコード結果の対応表

エンコード結果は Firefox 2.0, Safari 3.0, Opera 9.2, IE 7 で確認したもので、いずれも同じ結果を返します。

RFC 2396 の記述 JavaScript によるエンコード結果
URI構文内で許容されない 予約済み 予約済みでない escape encodeURI encodeURI
Component
  0x20 ✓ space %20 %20 %20
! 0x21 ✓ mark %21 ! !
" 0x22 ✓ delims %22 %22 %22
# 0x23 ✓ delims %23 # %23
$ 0x24 %24 $ %24
% 0x25 ✓ delims %25 %25 %25
& 0x26 %26 & %26
' 0x27 ✓ mark %27 ' '
( 0x28 ✓ mark %28 ( (
) 0x29 ✓ mark %29 ) )
* 0x2a ✓ mark * * *
+ 0x2b + + %2B
, 0x2c %2C , %2C
- 0x2d ✓ mark - - -
. 0x2e ✓ mark . . .
/ 0x2f / / %2F
: 0x3a %3A : %3A
; 0x3b %3B ; %3B
< 0x3c ✓ delims %3C %3C %3C
= 0x3d %3D = %3D
> 0x3e ✓ delims %3E %3E %3E
? 0x3f %3F ? %3F
@ 0x40 @ @ %40
[ 0x5b ✓ unwise %5B %5B %5B
\ 0x5c ✓ unwise %5C %5C %5C
] 0x5d ✓ unwise %5D %5D %5D
^ 0x5e ✓ unwise %5E %5E %5E
_ 0x5f ✓ mark _ _ _
` 0x60 ✓ unwise %60 %60 %60
{ 0x7b ✓ unwise %7B %7B %7B
| 0x7c ✓ unwise %7C %7C %7C
} 0x7d ✓ unwise %7D %7D %7D
~ 0x7e ✓ mark %7E ~ ~
0x6f22参考調査 %u6F22 %E6%BC%A2 %E6%BC%A2
0x8868参考調査 %u8868 %E8%A1%A8 %E8%A1%A8

使い分け

escape

encodeURI

  • RFC 2396 の「URI構文内で許容されない」文字をエンコードします。 例外として '#' はエンコードされません。
  • encodeURI は、'?', '&', '=' をエンコードしないため、クエリ文字列の作成には使えません。

encodeURIComponent

  • RFC 2396 の「URI構文内で許容されない」文字と「予約済み」文字をエンコードします。

調査方法

検証ページ JavaScript による URI エンコード には、JavaScript の3つの関数(escape, encodeURI, encodeURIComponent) によるエンコード結果が表示されます。

ソースコード

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>JavaScript による URI エンコード</title>
</head>
<body>
<pre>
<script type="text/javascript">
//<![CDATA[
(function() {

code = [
    ' ', '!', '"',  '#', '$', '%', '&', '\'', '(', ')', '*',
    '+', ',', '-',  '.', '/', ':', ';', '<',  '=', '>', '?',
    '@', '[', '\\', ']', '^', '_', '`', '{',  '|', '}', '~',
    '漢', '表'
];

document.write('<h1>escape</h1>');
for (var i in code) {
    document.write(code[i] + ' ' + escape(code[i]) + '<br />');
}

document.write('<h1>encodeURI</h1>');
for (var i in code) {
    document.write(code[i] + ' ' + encodeURI(code[i]) + '<br />');
}

document.write('<h1>encodeURIComponent</h1>');
for (var i in code) {
    document.write(code[i] + ' ' + encodeURIComponent(code[i]) + '<br />');
}

}());
//]]>
</script>
</pre>
</body>
</html>

改版履歴

日付 内容
2007-10-21 [削除] 「encodeURIComponent は、RFC 2396 に合致する。」の記述を削除した (encodeURIComponent だけで全て OK、のような誤解を与えるため)。
2007-05-19 [変更] 参照する文書を RFC 1738 から RFC 2396 へ変更した。
2007-05-17 [初版]