URLSearchParams に置き換える
動きは変えずに、クエリ文字列の組み立てだけを書き換えます。 第2章で残った2つの問題が、どちらも消えます。
この節で作るもの
Section titled “この節で作るもの”見た目も操作も前の節と同じです。違うのは、生成される URL の記号の扱いとコードの短さだけです。
今回さわるファイル:
index.htmlの組み立て部分を書き換える
前の節を終えていない人は、ここから始められます。
文字列結合でつらかったこと
Section titled “文字列結合でつらかったこと”第2章の終わりで、2つの問題が残りました。
- 区切り文字の使い分け … 先頭なら
?、2つ目以降なら&。空欄を飛ばすので、 どれが先頭になるかは実行するまで決まらない。そのため足すたびにifで確かめている - 記号が壊れる … 値に
&や空白が入ると、受け取り側が別の意味に読んでしまう
どちらも、URL を扱う人なら誰でもぶつかります。だから URLSearchParams という道具が
ブラウザに最初から入っています。
壊れ方をもう一度確認する
Section titled “壊れ方をもう一度確認する”書き換える前に、いま何が起きているかをもう一度見ておきます。 下のデモは、同じ入力から文字列結合と URLSearchParams の2通りで URL を作ります。
2つのリンクを順に押して、開いた先の表を見比べてください。 どちらも別タブで開きます。
件名の A&B社 向け/報告 をそのままつないだ上のリンクを開くと、受け取り側の表はこうなります。
| キー | 値 |
|---|---|
title | A |
B社 向け/報告 | (空) |
& のところで切れて、件名が「A」だけになり、残りが別のパラメータとして増えています。
こちらの意図した「A&B社 向け/報告 という1つの件名」は届いていません。
下のリンクを開くと、表は1行だけで、値も入力したとおりです。
| キー | 値 |
|---|---|
title | A&B社 向け/報告 |
件名を書き換えると、リンクもその場で作り直されます。空白や / # + でも試してみてください。
<!doctype html><html lang="ja"> <head> <meta charset="utf-8" /> <title>文字列結合とURLSearchParamsの違い</title> <style> body { font-family: "Segoe UI", "Meiryo", sans-serif; line-height: 1.7; margin: 16px; }
input { width: 22em; }
h2 { font-size: 1em; margin: 1.4em 0 0.3em; }
a { word-break: break-all; }
.note { margin: 0.3em 0 0; color: #555; }
.ng { color: #b00020; }
.ok { color: #1b6b2f; } </style> </head> <body> <p> 件名 <input id="title" value="A&B社 向け/報告" /> </p>
<p class="note"> 下の2つは、同じ入力から作った URL です。<b>押して受け取り側を見比べてください。</b> </p>
<h2>文字列結合で作ったURL</h2> <p><a id="joined" target="_blank"></a></p> <p class="note ng"> 押すと、件名が「A」だけになり、残りが別のパラメータとして増えています。 </p>
<h2>URLSearchParams で作ったURL</h2> <p><a id="encoded" target="_blank"></a></p> <p class="note ok"> 押すと、入力したとおりの値が1つのパラメータとして届いています。 </p>
<script> const titleInput = document.getElementById('title'); const joined = document.getElementById('joined'); const encoded = document.getElementById('encoded');
function update() { // 文字列結合で組み立てる(値の中の記号をそのまま URL に入れてしまう) const joinedUrl = 'docs.html?title=' + titleInput.value; joined.setAttribute('href', joinedUrl); joined.textContent = joinedUrl;
// URLSearchParams で組み立てる(記号は自動で変換される) const params = new URLSearchParams(); params.append('title', titleInput.value); const encodedUrl = 'docs.html?' + params.toString(); encoded.setAttribute('href', encodedUrl); encoded.textContent = encodedUrl; }
titleInput.addEventListener('input', update); update(); </script> </body></html><!doctype html><html lang="ja"> <head> <meta charset="utf-8" /> <title>資料検索(受け取り側)</title> <style> body { font-family: "Segoe UI", "Meiryo", sans-serif; line-height: 1.7; margin: 24px; } table { border-collapse: collapse; } th, td { border: 1px solid #999; padding: 4px 10px; text-align: left; } th { background: #e2efda; } .note { color: #555; } .url { word-break: break-all; } </style> </head> <body> <h1>資料検索(受け取り側)</h1>
<p class="note"> 検索システムの代わりに置いてある、受け取ったパラメータを並べるだけのページです。 実際に使うときは、ここが本物の検索システムのURLに変わります。 </p>
<p>受け取ったURL:<span id="url" class="url"></span></p>
<h2>受け取ったパラメータ</h2>
<table> <thead> <tr> <th>キー</th> <th>値</th> </tr> </thead> <tbody id="rows"></tbody> </table>
<p id="empty" class="note" hidden>パラメータは1つも付いていません。</p>
<script> const url = document.getElementById('url'); const rows = document.getElementById('rows'); const empty = document.getElementById('empty');
url.textContent = location.href;
// location.search は「?」から後ろの文字列。 // 受け取る側も URLSearchParams で読み解くのがいちばん簡単。 const params = new URLSearchParams(location.search);
let count = 0;
params.forEach((value, key) => { const row = document.createElement('tr'); const keyCell = document.createElement('td'); const valueCell = document.createElement('td');
keyCell.textContent = key; valueCell.textContent = value;
row.append(keyCell, valueCell); rows.append(row);
count = count + 1; });
if (count === 0) { empty.hidden = false; } </script> </body></html>URLSearchParams を使う
Section titled “URLSearchParams を使う”let query = '' から始まる組み立てを、まるごと書き換えます。
index.html を変更する
Section titled “index.html を変更する”8383 return;8484 }8585
86 // 「?」から後ろの部分(クエリ文字列)を1つずつ足していく。87 let query = '';86 // クエリ文字列を組み立てる道具。87 // 「&」でつなぐのも、空白や日本語の変換も URLSearchParams がやってくれる。88 const params = new URLSearchParams();8889
89 // 2つ目以降の前には「&」が必要なので、90 // すでに何か入っているかを毎回確かめることになる。9190 if (deptInput.value !== '') {92 if (query !== '') {93 query = query + '&';94 }95 query = query + 'dept=' + deptInput.value;91 params.append('dept', deptInput.value);9692 }9793
9894 if (titleInput.value !== '') {99 if (query !== '') {100 query = query + '&';101 }102 query = query + 'title=' + titleInput.value;95 params.append('title', titleInput.value);10396 }10497
10598 if (authorInput.value !== '') {106 if (query !== '') {107 query = query + '&';108 }109 query = query + 'author=' + authorInput.value;99 params.append('author', authorInput.value);110100 }111101
112102 if (dateInput.value !== '') {113 if (query !== '') {114 query = query + '&';115 }116 query = query + 'date=' + dateInput.value;103 params.append('date', dateInput.value);117104 }118105
119 const url = 'docs.html?' + query;106 const url = 'docs.html?' + params.toString();120107
121108 result.innerHTML = '<a href="' + url + '" target="_blank">' + url + '</a>';122109});4つの if をどれも params.append に書き換え、最後に params.toString() で文字列にしています。
使っているのは2つだけです。
params.append('dept', 値)… キーと値の組を1つ足すparams.toString()… 足したものを1本のクエリ文字列にする
「?」と「&」の分岐が消える
Section titled “「?」と「&」の分岐が消える”書き換え後の if を見てください。
if (deptInput.value !== '') { params.append('dept', deptInput.value);}内側の if (query !== '') が無くなりました。区切り文字をどこに入れるかは toString() が
決めるので、こちらが「いま何番目か」を知っている必要がないからです。
4項目で8個あった if が4個になり、項目が増えても1項目につき1個のままです。
日本語も記号も通る
Section titled “日本語も記号も通る”件名に A&B社 報告 と入れて生成してください。できる URL はこうなります。
docs.html?dept=25&title=A%26B%E7%A4%BE+%E5%A0%B1%E5%91%8A読みにくいですが、これで正しい形です。& は %26 に、空白は + に、日本語は %E7%A4%BE のような
並びに置き換わっています。この変換を URL エンコードといいます。
リンクを押して受け取り側を見ると、title = A&B社 報告 と元どおりに表示されます。
受け取る側が同じ規則で元に戻すからです。
第2章で割れていた値が、何も足していないのに1つの値として届くようになりました。
コラム: 受け取り側も URLSearchParams
Section titled “コラム: 受け取り側も URLSearchParams”同梱の docs.html が、どうやって値を読んでいるかを見てみます。
const params = new URLSearchParams(location.search);
params.forEach((value, key) => { // key と value を表に並べる});location.search は、いま開いている URL の ? から後ろの文字列です。
それを URLSearchParams に渡すと、キーと値の組として読み出せます。
作る側は append して toString()、読む側は渡して forEach。
同じ道具を両側で使うので、エンコードの規則がずれません。
第2章と同じように動けば成功です。見た目も操作も変わりません。 変わったのは、生成される URL の記号の扱いと、コードの短さだけです。
この節を終えたときのディレクトリ
Section titled “この節を終えたときのディレクトリ”<!doctype html><html lang="ja"> <head> <meta charset="utf-8" /> <title>資料検索(受け取り側)</title> <style> body { font-family: "Segoe UI", "Meiryo", sans-serif; line-height: 1.7; margin: 24px; } table { border-collapse: collapse; } th, td { border: 1px solid #999; padding: 4px 10px; text-align: left; } th { background: #e2efda; } .note { color: #555; } .url { word-break: break-all; } </style> </head> <body> <h1>資料検索(受け取り側)</h1>
<p class="note"> 検索システムの代わりに置いてある、受け取ったパラメータを並べるだけのページです。 実際に使うときは、ここが本物の検索システムのURLに変わります。 </p>
<p>受け取ったURL:<span id="url" class="url"></span></p>
<h2>受け取ったパラメータ</h2>
<table> <thead> <tr> <th>キー</th> <th>値</th> </tr> </thead> <tbody id="rows"></tbody> </table>
<p id="empty" class="note" hidden>パラメータは1つも付いていません。</p>
<script> const url = document.getElementById('url'); const rows = document.getElementById('rows'); const empty = document.getElementById('empty');
url.textContent = location.href;
// location.search は「?」から後ろの文字列。 // 受け取る側も URLSearchParams で読み解くのがいちばん簡単。 const params = new URLSearchParams(location.search);
let count = 0;
params.forEach((value, key) => { const row = document.createElement('tr'); const keyCell = document.createElement('td'); const valueCell = document.createElement('td');
keyCell.textContent = key; valueCell.textContent = value;
row.append(keyCell, valueCell); rows.append(row);
count = count + 1; });
if (count === 0) { empty.hidden = false; } </script> </body></html><!doctype html><html lang="ja"> <head> <meta charset="utf-8" /> <title>資料検索のURLを作る</title> <style> table { border-collapse: collapse; }
th, td { border: 1px solid #999; padding: 4px 10px; text-align: left; }
th { background: #e2efda; } </style> </head> <body> <h1>資料検索のURLを作る</h1>
<table> <thead> <tr> <th>項目</th> <th>パラメータ名</th> <th>値</th> <th>参考値</th> </tr> </thead> <tbody> <tr> <td>部署コード</td> <td>dept</td> <td><input id="dept" /></td> <td>25、ALL</td> </tr> <tr> <td>件名</td> <td>title</td> <td><input id="title" /></td> <td>月次報告</td> </tr> <tr> <td>作成者</td> <td>author</td> <td><input id="author" /></td> <td>山田</td> </tr> <tr> <td>作成日</td> <td>date</td> <td><input id="date" /></td> <td>2026-04-01</td> </tr> </tbody> </table>
<p> <button id="generateButton">生成</button> </p>
<p> 生成されたURL:<span id="result"></span> </p>
<script> const deptInput = document.getElementById('dept'); const titleInput = document.getElementById('title'); const authorInput = document.getElementById('author'); const dateInput = document.getElementById('date'); const generateButton = document.getElementById('generateButton'); const result = document.getElementById('result');
generateButton.addEventListener('click', () => { // 部署コードが無いと検索システム側がエラーになるので、ここで止める。 if (deptInput.value === '') { alert('部署コードは必須です。'); return; }
// クエリ文字列を組み立てる道具。 // 「&」でつなぐのも、空白や日本語の変換も URLSearchParams がやってくれる。 const params = new URLSearchParams();
if (deptInput.value !== '') { params.append('dept', deptInput.value); }
if (titleInput.value !== '') { params.append('title', titleInput.value); }
if (authorInput.value !== '') { params.append('author', authorInput.value); }
if (dateInput.value !== '') { params.append('date', dateInput.value); }
const url = 'docs.html?' + params.toString();
result.innerHTML = '<a href="' + url + '" target="_blank">' + url + '</a>'; }); </script> </body></html>