JavaScript/URL
URLオブジェクト
はじめに
現代のウェブ開発において、URLの操作は非常に頻繁に行われる作業です。JavaScriptのURLオブジェクトは、URL文字列を解析し、その構成要素を簡単に扱うための標準的なインターフェースを提供します。このオブジェクトを使用することで、URLの各部分(プロトコル、ホスト名、パス、クエリパラメータなど)を個別に取得したり、変更したりすることができます。
URLオブジェクトの基本
URLオブジェクトはURLを表現するために使用され、以下のような構文で新しいURLインスタンスを作成します。
const url = new URL(urlString, [baseURL]);
ここで、urlString
は解析するURL文字列で、オプションのbaseURL
は相対URLを絶対URLに変換するための基準となるURLです。
基本的な使用例
// 絶対URLの作成 const absoluteURL = new URL('https://example.com/path/to/page?query=string#hash'); // 相対URLの作成(ベースURLが必要) const relativeURL = new URL('/path/to/page', 'https://example.com'); console.log(relativeURL.href); // "https://example.com/path/to/page"
URLオブジェクトのプロパティ
URLオブジェクトは、URLの各部分にアクセスするための多くの読み取り/書き込み可能なプロパティを持っています。以下の表はそれらのプロパティとその説明です。
プロパティ | 説明 | 例(https://user:pass@example.com:8080/path/to/page?query=string#hash の場合) |
---|---|---|
href |
完全なURL文字列 | "https://user:pass@example.com:8080/path/to/page?query=string#hash" |
protocol |
プロトコルスキーム(: を含む) |
"https:" |
host |
ホスト名とポート | "example.com:8080" |
hostname |
ホスト名のみ | "example.com" |
port |
ポート番号 | "8080" |
pathname |
URLのパス部分 | "/path/to/page" |
search |
クエリ文字列(? を含む) |
"?query=string" |
hash |
フラグメント識別子(# を含む) |
"#hash" |
username |
ユーザー名 | "user" |
password |
パスワード | "pass" |
origin |
プロトコル + ホスト(読み取り専用) | "https://example.com:8080" |
searchParams |
URLSearchParams オブジェクト(読み取り専用) | |
これらのプロパティを使って、URLの各部分に簡単にアクセスしたり変更したりすることができます。
const url = new URL('https://example.com:8080/path?name=value#section'); console.log(url.hostname); // "example.com" console.log(url.port); // "8080" console.log(url.pathname); // "/path" console.log(url.search); // "?name=value" console.log(url.hash); // "#section" // プロパティの変更 url.hostname = 'example.org'; url.port = '443'; console.log(url.href); // "https://example.org:443/path?name=value#section"
URLSearchParamsオブジェクト
URLオブジェクト
のsearchParams
プロパティは、クエリパラメータを操作するためのURLSearchParams
オブジェクトを返します。このオブジェクトを使用すると、クエリ文字列を簡単に解析したり、パラメータを追加、変更、削除したりすることができます。
const url = new URL('https://example.com/search?name=John&age=30'); const params = url.searchParams; // パラメータの取得 console.log(params.get('name')); // "John" console.log(params.get('age')); // "30" // パラメータの追加 params.append('city', 'Tokyo'); console.log(url.href); // "https://example.com/search?name=John&age=30&city=Tokyo" // パラメータの設定(既存の値を上書き) params.set('age', '31'); console.log(url.href); // "https://example.com/search?name=John&age=31&city=Tokyo" // パラメータの削除 params.delete('city'); console.log(url.href); // "https://example.com/search?name=John&age=31" // 全てのパラメータを取得 for (const [key, value] of params.entries()) { console.log(`${key}: ${value}`); } // "name: John" // "age: 31" // パラメータの存在確認 console.log(params.has('name')); // true console.log(params.has('city')); // false
URLオブジェクトの実践的な使用例
現在のURLからパラメータを取得
// 現在のページのURLからパラメータを取得 function getParameterValue(paramName) { const url = new URL(window.location.href); return url.searchParams.get(paramName); } // 使用例(現在のURLが https://example.com/page?id=123&name=John の場合) const id = getParameterValue('id'); // "123" const name = getParameterValue('name'); // "John"
リンクの生成
function createLinkWithParams(baseUrl, params) { const url = new URL(baseUrl); // パラメータの追加 for (const [key, value] of Object.entries(params)) { url.searchParams.append(key, value); } return url.href; } // 使用例 const link = createLinkWithParams('https://example.com/search', { q: 'JavaScript', lang: 'ja', page: 1 }); console.log(link); // "https://example.com/search?q=JavaScript&lang=ja&page=1"
相対URLの解決
function resolveRelativeUrl(relativeUrl, baseUrl) { return new URL(relativeUrl, baseUrl).href; } // 使用例 const absoluteUrl = resolveRelativeUrl('../images/logo.png', 'https://example.com/products/item/'); console.log(absoluteUrl); // "https://example.com/products/images/logo.png"
ブラウザの互換性と注意点
URLオブジェクトは比較的新しいAPIですが、現在では主要なブラウザはすべてサポートしています。ただし、非常に古いブラウザでは利用できない場合があります。
また、URLオブジェクトはJavaScriptのどの環境でも使えるわけではありません。Node.jsはバージョン7.0.0以降でサポートされています。古いNode.jsバージョンやその他の環境では、url
モジュールを使用するか、ポリフィルを導入する必要があるかもしれません。
// Node.jsでの使用例 const { URL } = require('url'); const myUrl = new URL('https://example.com/path');
まとめ
URLオブジェクトは、JavaScriptでURLを操作するための強力で便利なツールです。このオブジェクトを使用することで、URL文字列を簡単に解析し、各部分にアクセスしたり変更したりすることができます。特に、searchParams
プロパティを通じてクエリパラメータを扱うことが非常に簡単になります。
現代のウェブ開発では、URLの操作は日常的な作業の一つです。URLオブジェクトを使いこなすことで、より効率的に開発を進めることができるでしょう。
附録
静的プロパティ
静的アクセサ
静的メソッド
URLのインスタンスプロパティ
URLのインスタンスアクセサ
- get URL.prototype.hash
- get URL.prototype.host
- get URL.prototype.hostname
- get URL.prototype.href
- get URL.prototype.origin
- get URL.prototype.password
- get URL.prototype.pathname
- get URL.prototype.port
- get URL.prototype.protocol
- get URL.prototype.search
- get URL.prototype.searchParams
- get URL.prototype.username