location.protocol、location.host、location.pathnameでURLを分解する
JavaScriptで現在のURLを取得する方法
location.href を使う
最も簡単な方法は、location.href
プロパティを使うことです。これは、現在のページの完全なURLを返します。
const url = location.href;
console.log(url); // 例: https://example.com/index.html
location.protocol、location.host、location.pathname を使う
より細かい制御が必要な場合は、location.protocol
、location.host
、location.pathname
などのプロパティを個別に使うことができます。
location.protocol
: プロトコル (例:https
)location.host
: ホスト名 (例:example.com
)location.pathname
: パス名 (例:/index.html
)
const protocol = location.protocol;
const host = location.host;
const pathname = location.pathname;
console.log(protocol); // 例: https
console.log(host); // 例: example.com
console.log(pathname); // 例: /index.html
URLSearchParams オブジェクトを使うと、URLのパラメータを取得することができます。
const url = new URL(location.href);
const params = new URLSearchParams(url.search);
const param1 = params.get('param1');
const param2 = params.get('param2');
console.log(param1); // 例: value1
console.log(param2); // 例: value2
その他の方法
上記以外にも、以下のような方法でURLを取得することができます。
- document.URL
- window.location
- history.state
これらの方法は、上記の方法とほぼ同じように動作します。
JavaScriptで現在のURLを取得するには、いくつかの方法があります。どの方法を使うかは、必要な情報と目的によって異なります。
location.href を使う
const url = location.href;
console.log(url); // 例: https://example.com/index.html
location.protocol、location.host、location.pathname を使う
const protocol = location.protocol;
const host = location.host;
const pathname = location.pathname;
console.log(protocol); // 例: https
console.log(host); // 例: example.com
console.log(pathname); // 例: /index.html
URLSearchParams を使う
const url = new URL(location.href);
const params = new URLSearchParams(url.search);
const param1 = params.get('param1');
const param2 = params.get('param2');
console.log(param1); // 例: value1
console.log(param2); // 例: value2
その他の方法
// document.URLを使う
const url = document.URL;
console.log(url); // 例: https://example.com/index.html
// window.locationを使う
const url = window.location;
console.log(url); // 例: Location {href: "https://example.com/index.html", …}
// history.stateを使う
const url = history.state;
console.log(url); // 例: {url: "https://example.com/index.html"}
JavaScriptで現在のURLを取得するその他の方法
location.search
プロパティは、URLのクエリ文字列を取得します。クエリ文字列は、? の後に続く部分です。
const query = location.search;
console.log(query); // 例: ?param1=value1¶m2=value2
const hash = location.hash;
console.log(hash); // 例: #fragment
document.referrer
プロパティは、現在のページに遷移する前にユーザーがいたページのURLを取得します。
const referrer = document.referrer;
console.log(referrer); // 例: https://example.com/previous-page.html
window.history
オブジェクトは、ブラウザの履歴に関する情報を提供します。
const history = window.history;
// 履歴の長さを取得
const length = history.length;
// 履歴の現在のエントリを取得
const currentEntry = history.state;
// 履歴を1つ前に戻る
history.back();
// 履歴を1つ進む
history.forward();
javascript url