JavaScript開発でURLパラメータを扱う際に避けては通れない `encodeURIComponent()` 関数について、実践的な使い方と注意点を解説します。

encodeURIComponent()とは

`encodeURIComponent()` は、URLで使用できない特殊文字をエンコードしてURLで安全に使える形式に変換するJavaScriptの組み込み関数です。

基本的な使い方

const text = "Hello World!";
const encoded = encodeURIComponent(text);
console.log(encoded); // "Hello%20World%21"

よくある使用シーン

1. URLパラメータの作成

const searchTerm = "JavaScript & TypeScript";
const url = `https://example.com/search?q=${encodeURIComponent(searchTerm)}`;

2. APIリクエストのパラメータ設定

const params = {
  name: "John Doe",
  email: "john@example.com"
};

const queryString = Object.keys(params)
  .map(key => `${key}=${encodeURIComponent(params[key])}`)
  .join('&');

encodeURIComponent()とencodeURI()の違い

`encodeURIComponent()` はURLパラメータとして使用する文字列全体をエンコードしますが、`encodeURI()` はURL全体をエンコードする際に使用され、`:/`などの文字はエンコードしません。

const text = "https://example.com/?q=test";
console.log(encodeURIComponent(text));
// "https%3A%2F%2Fexample.com%2F%3Fq%3Dtest"
console.log(encodeURI(text));
// "https://example.com/?q=test"

エンコード対象の文字

`encodeURIComponent()` は以下のような文字をエンコードします:

  • スペース → %20
  • ! → %21
  • # → %23
  • $ → %24
  • & → %26
  • ' → %27
  • ( → %28
  • ) → %29
  • * → %2A
  • + → %2B
  • , → %2C
  • / → %2F
  • : → %3A
  • ; → %3B
  • = → %3D
  • ? → %3F
  • @ → %40
  • [ → %5B
  • ] → %5D

デコードの方法

エンコードされた文字列を元に戻すには `decodeURIComponent()` を使用します:

const encoded = encodeURIComponent("Hello World!");
const decoded = decodeURIComponent(encoded);
console.log(decoded); // "Hello World!"

エラー処理

文字列以外の値を渡した場合や不正なエンコード文字列をデコードしようとした場合、エラーが発生する可能性があります。そのため、try-catch文での対応を推奨します:

try {
  const decoded = decodeURIComponent('%E');
} catch(e) {
  console.error('デコードに失敗しました:', e);
}

まとめ

`encodeURIComponent()` は:

  • URLパラメータのエンコードに最適
  • 特殊文字を安全にURLで使用可能な形式に変換
  • APIリクエストのパラメータ作成時に必須
  • `decodeURIComponent()` でデコード可能

適切なURLエンコーディングは、Webアプリケーションの安定性と安全性を確保する上で重要な要素です。