JavaScriptのencodeURIとencodeURIComponentの違い
encodeURI()はURLの構造上の区切りを残します。encodeURIComponent()は検索語など一つの値をエンコードします。クエリーを作る場合は元の値をURLSearchParamsに渡せます。対応する段階でデコードし、不正な表記を処理します。
四つの関数が処理する範囲
URI(Uniform Resource Identifier)は資源を識別し、URLはその場所を示します。パーセントエンコードはバイトを%HHで表すため、非ASCII文字は複数のUTF-8バイトになることがあります。暗号化ではありません。encodeURIComponent()は英数字や- _ . ! ~ * ' ( )を残し、encodeURI()より多くの区切りを変換します。
| 関数 | 用途 | 区切り文字の扱い |
|---|---|---|
encodeURI() |
URI全体 | 次のような構造用区切りを保持 :, /, ?, &, =, # |
encodeURIComponent() |
パス部分やクエリー値 | 区切りも値としてエンコード |
decodeURI() |
URI全体をデコード | 一部の予約区切りは符号化したまま |
decodeURIComponent() |
個別値をデコード | 区切りを含めパーセント表記をデコード |
encodeURI("a&b=c"); // "a&b=c"
encodeURIComponent("a&b=c"); // "a%26b%3Dc"
decodeURI("%26"); // "%26"
decodeURIComponent("%26"); // "&"
検索URLを組み立てる完全な例
UTF-8のurl-encoding.htmlとして保存して開きます。実際には通信せずURLを作って読み直します。検索語はsに入れます。
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Encode and decode URL values</title>
</head>
<body>
<h1>Put a search term in a URL</h1>
<label for="keyword">Search term</label>
<input id="keyword" value="C++ & Café">
<button id="encode" type="button">Encode</button>
<button id="restore" type="button">Restore defaults</button>
<pre id="output"></pre>
<label for="encoded">Encoded value</label>
<input id="encoded" value="Caf%C3%A9">
<button id="decode" type="button">Decode</button>
<pre id="decoded"></pre>
<script>
const keyword = document.getElementById("keyword");
const output = document.getElementById("output");
function encode() {
try {
const value = keyword.value;
const component = encodeURIComponent(value);
const url = new URL("https://www.codingfactory.net/");
url.searchParams.set("s", value);
output.textContent = [
`encodeURI: ${encodeURI(value)}`,
`encodeURIComponent: ${component}`,
`Decoded again: ${decodeURIComponent(component)}`,
`Search URL: ${url.href}`,
`Value from URL: ${url.searchParams.get("s")}`
].join("\n");
} catch (error) {
output.textContent = error.name;
}
}
document.getElementById("encode").addEventListener("click", encode);
document.getElementById("restore").addEventListener("click", () => {
keyword.value = "C++ & Café";
encode();
});
document.getElementById("decode").addEventListener("click", () => {
try {
document.getElementById("decoded").textContent =
decodeURIComponent(document.getElementById("encoded").value);
} catch (error) {
document.getElementById("decoded").textContent = error.name;
}
});
encode();
</script>
</body>
</html>
+と&はencodeURI()では残り、encodeURIComponent()では%2Bと%26になります。?s=の後で裸の&は別の項目を始めます。URLSearchParamsは空白を+、実際のプラスを%2Bにします。C++ & Caféを読み戻せるか確認します。a&b=1も試し、復元します。set()には元の文字列を渡します。
デコードエラーと二重エンコード
初期値をデコードするとCaféです。%や%E0%A4%AではURIErrorになります。UTF-16のサロゲートが単独である場合はエンコードも失敗し得ます。ブラウザーによる違いを避けるためエラー名だけ表示します。URIErrorを参照してください。
const once = encodeURIComponent("&"); // "%26"
const twice = encodeURIComponent(once); // "%2526"
decodeURIComponent(twice); // "%26": decodes one layer only
decodeURIComponent("a+b"); // "a+b": does not turn a plus into a space
各段階では一度だけデコードします。URLSearchParams.get()はデコード済みの値を返します。さらに変換すると元のデータが変わることがあります。decodeURIComponent()はプラスを残し、クエリー解析では空白として扱われます。
URLの移動先を別に検証する
エンコードは移動先の検証とは別です。外部入力からURLを作るときはプロトコルとホストを確認します。文字の表示はtextContentで行います。
パスの一部分とクエリー値を一緒に作る
Consoleで実行します。項目名だけをエンコードしてスラッシュを一つのパス部分に収め、カテゴリーは元の値でsearchParams.set()に渡します。通信は発生しません。
{
const item = "Part A/B";
const category = "Café + tea";
const url = new URL("https://example.com/");
url.pathname = "/items/" + encodeURIComponent(item);
url.searchParams.set("category", category);
console.log(url.href);
console.log(decodeURIComponent(url.pathname.split("/").at(-1)));
console.log(url.searchParams.get("category"));
}
最初にhttps://example.com/items/Part%20A%2FB?category=Caf%C3%A9+%2B+tea、次にPart A/BとCafé + teaが表示されます。パスを分割してから個別にデコードします。.と..はパスの解析で正規化されます。サーバーが符号化したスラッシュを別扱いする場合は識別子をクエリーで渡せます。




