encodeURI()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

encodeURI() 関数は、URI (Uniform Resource Identifier; 統一資源識別子) をエンコードし、各文字のインスタンスをそれぞれ UTF-8 符号の文字を表す 1 個から 4 個のエスケープシーケンスに置き換えます (サロゲート文字のペアのみ 4 個のエスケープシーケンスになります)。

試してみましょう

const uri = "https://mozilla.org/?x=шеллы"; const encoded = encodeURI(uri); console.log(encoded); // Expected output: "https://mozilla.org/?x=%D1%88%D0%B5%D0%BB%D0%BB%D1%8B" try { console.log(decodeURI(encoded)); // Expected output: "https://mozilla.org/?x=шеллы" } catch (e) { // Catches a malformed URI console.error(e); } 

構文

encodeURI(URI) 

引数

URI

完全 URI です。

返値

URI (Uniform Resource Identifier) としてエンコードされた指定された文字列を表す新しい文字列です。

解説

encodeURI() 関数では、 URI において特別な意味を持つ文字 (予約文字) はエンコードされません。下記の例は URI "scheme" に含まれる可能性がある全ての箇所を示しています。特定の文字がどのように特殊な意味を表すために使われているかに注意してください。

http://username:password@www.example.com:80/path/to/file.php?foo=316&bar=this+has+spaces#anchor 

したがって、 encodeURI() は完全な URI を表すのに必要な文字はエンコードしません。また、 encodeURI() は "unreserved marks" (予約されていないが "そのまま" URI に使用できる) 文字をエンコードしません。 (RFC2396 を確認してください。)

encodeURI() は下記以外の全ての文字をエスケープします。

エスケープされないもの: A-Z a-z 0-9 ; , / ? : @ & = + $ - _ . ! ~ * ' ( ) # 

encodeURI と encodeURIComponent

encodeURI() は以下のように encodeURIComponent() とは異なります。

js
var set1 = ";,/?:@&=+$#"; // 予約文字 var set2 = "-_.!~*'()"; // 予約されていない記号 var set3 = "ABC abc 123"; // 英数字 + 空白 console.log(encodeURI(set1)); // ;,/?:@&=+$# console.log(encodeURI(set2)); // -_.!~*'() console.log(encodeURI(set3)); // ABC%20abc%20123 (空白は %20 にエンコードされる) console.log(encodeURIComponent(set1)); // %3B%2C%2F%3F%3A%40%26%3D%2B%24%23 console.log(encodeURIComponent(set2)); // -_.!~*'() console.log(encodeURIComponent(set3)); // ABC%20abc%20123 (空白は %20 にエンコードされる) 

なお、encodeURI() のみでは、 HTTP の GET および POST リクエストを XMLHttpRequest のように適切に構成できません。なぜなら、 "&", "+", "=" は GET および POST リクエストにおいて特別な文字であり、それらがエンコードされないからです。 encodeURIComponent() の場合、それらがエンコードされます。

単独のサロゲート文字のエンコード

サロゲートペアになっていない 1 個のサロゲート文字をエンコードしようとすると URIError が発生することに注意してください。例えば、

js
// サロゲートペアは OK console.log(encodeURI("\uD800\uDFFF")); // 上位サロゲートのみだと "URIError: malformed URI sequence" エラーが発生 console.log(encodeURI("\uD800")); // 下位サロゲートのみだと "URIError: malformed URI sequence" エラーが発生 console.log(encodeURI("\uDFFF")); 

IPv6 のエンコード

また、 URL 記述のために最近の RFC3986 仕様に従おうとする場合、角括弧 [] は (IPv6 用の) 予約文字となっているため、角括弧が (ホスト名など) URL の一部を形成している場合はエンコードされていないほうがよいでしょう。そういう場合は以下のコードが役に立ちます。

js
function fixedEncodeURI(str) { return encodeURI(str).replace(/%5B/g, "[").replace(/%5D/g, "]"); } 

仕様書

Specification
ECMAScript® 2026 Language Specification
# sec-encodeuri-uri

ブラウザーの互換性

関連情報