javascript URLを分割代入と正規表現を使用して分割して取得する

javascript URLを分割代入と正規表現を使用して分割して取得する

javascriptで、URLを分割代入と正規表現を使用して分割して取得するサンプルコードを記述してます。

環境

  • OS windows10 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 103.0.5060.66

分割代入と正規表現を使用

以下のように、分割代入を使用してURLの値を分割して取得することができます。

const url = 'https://mebee.info/2019/10/28/post-2324/';

const str = url.match(/(https?:)\/\/([\w.-]+)(.*)/);
const [all, protocol, host, path] = str;

console.log('プロトコル :', protocol.replace( /:/g , '' ));
console.log('ホスト :', host);
console.log('パス :', path);

実行結果

サンプルコード

以下は、
「取得」ボタンをクリックすると、URLを分割代入を使用してプロトコルとホストとパスに分割して表示する
サンプルコードとなります。

※cssには「bootstrap material」を使用してます。

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <!-- MDB -->
  <link href="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/4.2.0/mdb.min.css" rel="stylesheet" />
</head>

<body>

  <div class="container text-center w-50" style="margin-top:150px">

    <h2><spna class="badge badge-primary">プロトコル</spna></h2>
    <h2><spna class="badge badge-primary">ホスト</spna></h2>
    <h2><spna class="badge badge-primary">パス</spna></h2>

    <button id="btn" type="button" class="btn btn-raised btn-danger">
      取得
    </button>

  </div>

  <script>

    function hoge() {
      // URLを取得
      const str = location.href.match(/(https?:)\/\/([\w.-]+)(.*)/);
      // 分割代入
      const [all, protocol, host, path] = str;
      // 表示用の要素
      document.getElementsByClassName("badge")[0].textContent = protocol.replace(/:/g, '');
      document.getElementsByClassName("badge")[1].textContent = host;
      document.getElementsByClassName("badge")[2].textContent = path;

    }    

    // ボタンを取得
    let elm = document.getElementById("btn");

    // クリックイベントを登録
    elm.onclick = function () {
      hoge();
    };


  </script>
</body>

</html>

プロトコルとホストとパスに分割されて取得されていることが確認できます。