JavaScript の location で現在の URL・ドメイン・パスを取得する

現在のアドレスは window.location.href、ホスト名は window.location.hostname、パスは window.location.pathname で取得できます。Location オブジェクトは現在の文書の URL に結び付いています。別のアドレスを解析するには new URL(address) を使います。

現在の URL の各部分を読む

表はサンプル https://example.com:8080/path/page.html?lang=ko&tag=js&tag=dom&q=hello+world#part を分解した結果です。host は既定以外のポートを含み、hostname はポートを含みません。ポートを省略するか HTTPS の既定値 443 を指定すると、port は空文字列です。各プロパティの定義は HTML Living Standard にあります。

プロパティ 値の例 意味
href https://example.com:8080/path/page.html?lang=ko&tag=js&tag=dom&q=hello+world#part URL 全体
origin https://example.com:8080 HTTP(S) のスキーム、ホスト名、ポート
protocol https: 末尾のコロンを含むスキーム
host example.com:8080 ホスト名と既定以外のポート
hostname example.com ポートを含まないホスト名
port 8080 既定以外のポート番号
pathname /path/page.html クエリとフラグメントを除いたパス
search ?lang=ko&tag=js&tag=dom&q=hello+world 疑問符を含むクエリ
hash #part ハッシュ記号を含むフラグメント

URL とクエリパラメーターを解析する

コードをブラウザーのコンソールで実行します。最初の二行は現在の文書のアドレスとパスを表示します。残りはサンプルの解析結果です。new URL() はネットワーク要求を送信せず、ページも移動しません。

const current = window.location;
console.log(current.href);
console.log(current.pathname);

const sample = new URL('https://example.com:8080/path/page.html?lang=ko&tag=js&tag=dom&q=hello+world#part');
console.log(sample.host);
console.log(sample.hostname);
console.log(sample.searchParams.get('lang'));   // ko
console.log(sample.searchParams.get('tag'));    // js
console.log(sample.searchParams.getAll('tag')); // ['js', 'dom']
console.log(sample.searchParams.get('q'));      // hello world

search は ? を含むクエリ文字列です。searchParams.get('tag') は最初の値 js、getAll('tag') は ['js', 'dom'] を出現順に返します。キーがなければ get() は null、getAll() は空の配列です。tag= の値は空文字列です。+ は空白になるため、q は hello world です。詳しくは URL Standard を参照してください。

完全なサンプル:現在の URL と入力した URL を比較

HTML を UTF-8 で location-example.html として保存し、ブラウザーで開きます。「URL を解析」は入力欄の絶対 URL を読み取ります。「現在のページの URL」は開いている文書のアドレスをコピーして解析します。「リセット」で例のアドレスに戻ります。

<!doctype html>
<html lang="ja">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>URL の各部分を確認する</title>
</head>
<body>
<label for="address">解析する絶対 URL</label>
<input id="address" type="url" size="60" value="https://example.com:8080/path/page.html?lang=ko&amp;tag=js&amp;tag=dom&amp;q=hello+world#part">
<button id="parse" type="button">URL を解析</button>
<button id="current" type="button">現在のページの URL</button>
<button id="reset" type="button">リセット</button>
<pre id="output" aria-live="polite"></pre>
<script>
const address = document.querySelector('#address');
const output = document.querySelector('#output');

function show(value) {
  try {
    const url = new URL(value);
    output.textContent = [
      `href: ${url.href}`,
      `origin: ${url.origin}`,
      `protocol: ${url.protocol}`,
      `host: ${url.host}`,
      `hostname: ${url.hostname}`,
      `port: ${url.port || "(なし)"}`,
      `pathname: ${url.pathname}`,
      `search: ${url.search || "(なし)"}`,
      `hash: ${url.hash || "(なし)"}`,
      `lang: ${url.searchParams.get('lang') ?? "(なし)"}`,
      `tag: ${JSON.stringify(url.searchParams.getAll('tag'))}`,
      `q: ${url.searchParams.get('q') ?? "(なし)"}`,
    ].join('\n');
  } catch (error) {
    output.textContent = "有効な絶対 URL を入力してください。";
  }
}

document.querySelector('#parse').addEventListener('click', () => show(address.value));
document.querySelector('#current').addEventListener('click', () => {
  address.value = window.location.href;
  show(address.value);
});
document.querySelector('#reset').addEventListener('click', () => {
  address.value = 'https://example.com:8080/path/page.html?lang=ko&tag=js&tag=dom&q=hello+world#part';
  show(address.value);
});
show(address.value);
</script>
</body>
</html>

初期結果では host に :8080 が付き、hostname には付きません。tag の配列には二つの値が入り、q には空白が入ります。/path/page.html だけを入力すると基準がないためエラーになります。相対パスを解決するには new URL(relativePath, baseURL) を使います。ファイルを直接開いた場合、現在のアドレスは file: で始まります。

アドレスの読み取りとページ遷移を区別する

location.href への代入や location.assign(url) の呼び出しはページ遷移を起こします。location.replace(url) は現在の履歴項目を置き換えるため、戻る操作で置き換えたページに戻りません。このサンプルはプロパティを表示するだけです。実際の遷移前にはプロジェクトで許可されたスキームとオリジンか確認してください。仕様は HTML Living Standard を参照してください。