JavaScriptの数値表示・URIエンコード・CSSセレクター

数値の表示には toLocaleString()、URIの一部分の符号化には encodeURIComponent()、クエリの組み立てには URL.searchParams を使います。CSSと querySelectorAll() は同じセレクター構文を使います。

表示用の数値を整形する

ロケールは桁区切りや小数点の表記を定めます。en-USで123456789は123,456,789、de-DEで1234.5は1.234,5になります。結果は文字列なので、計算には元の数値を残しておきます。 ECMA-402 Number.prototype.toLocaleString

console.log((123456789).toLocaleString("en-US"));
console.log((1234.5).toLocaleString("de-DE"));

URI全体と個別の構成要素を区別する

URIはリソースを識別します。encodeURI() は ?、&、# などの構造文字を保持します。encodeURIComponent() は一つの値の中にあるこれらの文字を符号化します。値に未処理の & があると、パラメーターの区切りに見えることがあります。decodeURI() は予約区切り文字を保持し、decodeURIComponent() は符号化された一部分を復元します。 ECMAScript URI Handling Functions

console.log(encodeURI("https://example.com/search?q=coffee&sort=new"));
console.log(encodeURIComponent("coffee&tea"));
console.log(decodeURIComponent("coffee%26tea"));

元の値からクエリを組み立てる

searchParams.set() には未変換の文字列を渡します。URLSearchParams は空白を + に、値そのものに含まれるプラス記号を %2B に変換します。get() で元の値を読み取れます。coffee%26tea をそのまま渡すと二重に符号化され、coffee%2526tea になります。 WHATWG URLSearchParams

const url = new URL("https://example.com/search");
url.searchParams.set("q", "coffee & tea");
url.searchParams.set("page", "1");
console.log(url.href);
console.log(url.searchParams.get("q"));

デコードエラーと古いデータに対処する

不正なパーセント表記や無効なUTF-8は URIError を引き起こします。例ではそのエラーで null を返し、その他は投げ直します。クエリ全体をデコードしてから分割せず、パラメーターごとに読み取ります。従来の escape() には %uXXXX 形式があるため、移行前に元のデータ形式を確認します。 ECMAScript URI Handling Functions

function decodeComponentSafely(text) {
  try {
    return decodeURIComponent(text);
  } catch (error) {
    if (error instanceof URIError) return null;
    throw error;
  }
}
console.log(decodeComponentSafely("%E0%A4%A"));

位置を基準に子要素を選ぶ

li:nth-child(2) は2番目の子要素が li の場合に一致し、li:nth-of-type(2) は兄弟の li だけを数えます。テキストやコメントは数えません。異なる種類を比べる場合は div などそれらを含められる親要素を使います。selectivizr は旧Internet Explorer向けでした。 W3C Selectors Level 4

#items > li:nth-child(2) {
  color: #a00000;
}
#items > li:last-child {
  font-weight: bold;
}

ひとつのHTML例で確認する

javascript-notes.html としてUTF-8で保存し、現在のブラウザーで開きます。検索リクエストを送らずURLを表示します。coffee & tea の構成要素には %20 と %26 が現れ、クエリの空白は + になります。デコードした行では元の入力が読め、CSSで2番目の項目が強調されます。

<!doctype html>
<html lang="ja">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>JavaScriptの数値表示・URIエンコード・CSSセレクター</title>
  <style>
    .selected { color: #a00000; font-weight: bold; }
    #output { white-space: pre-wrap; overflow-wrap: anywhere; }
  </style>
</head>
<body>
  <label for="query">検索語</label>
  <input id="query" value="coffee &amp; tea">
  <button id="build" type="button">URLを作成</button>
  <ul id="items"><li>1番目</li><li>2番目</li><li>3番目</li></ul>
  <pre id="output" aria-live="polite"></pre>
  <script>
    const input = document.getElementById("query");
    const output = document.getElementById("output");
    function show() {
      const value = input.value;
      const component = encodeURIComponent(value);
      const url = new URL("https://example.com/search");
      url.searchParams.set("q", value);
      output.textContent = [
        "構成要素" + ": " + component,
        "デコード結果" + ": " + decodeURIComponent(component),
        "検索URL" + ": " + url.href,
        "整形した数値" + ": " + (123456789).toLocaleString("en-US")
      ].join("\n");
    }
    for (const item of document.querySelectorAll("#items > li:nth-child(2)")) {
      item.classList.add("selected");
    }
    document.getElementById("build").addEventListener("click", show);
    show();
  </script>
</body>
</html>