URL 文字列エンコード/デコード — encodeURIComponent / decodeURIComponent
Webアプリでは「URLに文字列を安全に含めたい」場面がよくあります。検索キーワードやユーザー入力をそのままURLに入れると、スペースや日本語、記号で壊れてしまうことがあります。
そこで使うのが encodeURIComponent(エンコード)と decodeURIComponent(デコード)です。
基本のコード例
const keyword = "こんにちは 世界!";
// URLに安全に入れるためにエンコード
const encoded = encodeURIComponent(keyword);
console.log(encoded);
// → "%E3%81%93%E3%82%93%E3%81%AB%E3%81%A1%E3%81%AF%20%E4%B8%96%E7%95%8C!"
// 元に戻す(デコード)
const decoded = decodeURIComponent(encoded);
console.log(decoded);
// → "こんにちは 世界!"
JavaScriptencodeURIComponent(str): 文字列をURLで安全に使える形に変換。decodeURIComponent(str): エンコードされた文字列を元に戻す。
よく使うテンプレート集
検索クエリをURLに入れる
const q = "JavaScript 入門";
const url = "https://example.com/search?q=" + encodeURIComponent(q);
console.log(url);
// → https://example.com/search?q=JavaScript%20%E5%85%A5%E9%96%80
JavaScriptクエリ文字列を読み取って復元
const params = new URLSearchParams(location.search);
const q = decodeURIComponent(params.get("q"));
console.log("検索キーワード:", q);
JavaScript複数のパラメータを安全に結合
function buildUrl(base, params) {
const query = Object.entries(params)
.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
.join("&");
return `${base}?${query}`;
}
console.log(buildUrl("https://example.com/search", { q: "日本語", page: 2 }));
// → https://example.com/search?q=%E6%97%A5%E6%9C%AC%E8%AA%9E&page=2
JavaScript例題: 入力フォームから検索URLを生成
<input id="kw" placeholder="検索キーワード">
<button id="go">検索</button>
<script>
document.getElementById("go").addEventListener("click", () => {
const kw = document.getElementById("kw").value;
const url = "https://example.com/search?q=" + encodeURIComponent(kw);
location.href = url; // 安全に検索ページへ遷移
});
</script>
HTML- 効果: 入力したキーワードを安全にURLに組み込み、検索ページへ移動。
実務でのコツ
- 必ずエンコード: ユーザー入力をそのままURLに入れると壊れる。必ず
encodeURIComponent。 - デコードは必要なときだけ: URLから値を取り出すときは
decodeURIComponent。 - 特殊文字: スペースは
%20、日本語は UTF-8 のバイト列を%xx形式に変換。 - キーも値もエンコード: クエリパラメータは両方エンコードするのが安全。
encodeURIとの違い:encodeURIは「URL全体」をエンコード(?や&は残す)。encodeURIComponentは「パラメータ部分」をエンコード(?や&も変換)。
ありがちなハマりポイントと対策
encodeURIと混同:- 対策: パラメータには
encodeURIComponentを使う。
- 対策: パラメータには
- 二重エンコード:
- 対策: 既にエンコード済みの文字列を再度エンコードしない。
- デコード忘れ:
- 対策: 表示や処理に使うときは
decodeURIComponentで戻す。
- 対策: 表示や処理に使うときは
練習問題(ブックマークレット風)
// 現在のページURLをエンコードして検索サービスに渡す
const current = location.href;
const url = "https://example.com/share?u=" + encodeURIComponent(current);
console.log("共有リンク:", url);
JavaScript- 効果: 現在のページURLを安全にクエリに含めて共有リンクを作れる。
直感的な指針
- encodeURIComponent = 「URLに入れる前に安全に変換」
- decodeURIComponent = 「URLから取り出すときに元に戻す」
- パラメータ部分は必ず encodeURIComponent を使う。
- encodeURI は「URL全体」、encodeURIComponent は「部品」用。
これを覚えれば「検索キーワードをURLに入れる」「共有リンクを作る」「日本語や記号を安全に扱う」といった場面で安心して使えます。
