jQueryで現在のURLを取得して処理を分岐させたい時、ちょっとど忘れしてしまうことがあるのでまとめてみました。

URLを取得する方法

例えば、以下のようなURLのページがあったとして、このページのURL、ドメインやパスはlocationを使用して取得することができます。

「https://gri-t.com/example/example.html?page=2#id1」というページを例に見てみましょう。

// URLの取得
// https://gri-t.com/example/example.html?page=2#id1
var url = location.href;
  
// ドメインの取得 
// gri-t.com
var host = location.hostname;
  
// パスの取得 
// /example/example.html
var path = location.pathname;
  
// パラメータの取得
// ?page=2
var query = location.search;
  
// アンカーの取得
// #id1
var anchor = location.hash;

次に取得したURLやパスを条件に処理内容を指定する方法です。

$(window).on(load, function() {

 if (url == "https://example.com/"){
   // URLが https://example.com/ の場合に実行する処理
 }
 if (host == 'example.com') {
  // ドメインが example.com の場合に実行する処理
 }
 if (path == "/example/example.html"){
  // ドメイン以下のパス名が /example/example.html の場合に実行する処理
 }
 if (query == "?page=2"){
  // パラメータの値が ?page=2 の場合に実行する処理
 }
 if (anchor == "#id01"){
  // ハッシュが #id01 の場合に実行する処理
 }  
 
  //URL取得を含むif文 現在のURLにhogeが含まれていたら実行
 if(document.URL.match(/example/)) {
   $('body').addClass('example');
 }
});

以上が、jQueryでURLを取得して条件分岐させる方法でした。