javascript URLがlocalhostであるかを判定する

javascript URLがlocalhostであるかを判定する

javascriptで、URLがlocalhostであるかを判定するサンプルコードを記述してます。

環境

  • OS windows11 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 106.0.5249.103

URLがlocalhostであるかを判定

URLがlocalhostであるかを判定するには、「localhost」か「127.0.0.1」がURLに含まれているかを条件にして判定します。

const url = 'http://localhost:3000/';

console.log( url.includes('localhost') || url.includes('127.0.0.1') );
// true

関数化して、複数のパターンを判定してみます。
※ここでは正規表現で「URL」であるかも一緒に判定してます。

const pattern = new RegExp('^(https?:\\/\\/)?'+
  '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.?)+[a-z]{2,}|'+
  '((\\d{1,3}\\.){3}\\d{1,3}))'+
  '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+
  '(\\?[;&a-z\\d%_.~+=-]*)?'+
  '(\\#[-a-z\\d_]*)?$','i');

function isLocalhost(url) {

    if(!pattern.test(url)) return false; // URLであるかのCHECK

    return url.includes('localhost') || url.includes('127.0.0.1');
}


console.log( isLocalhost('https://localhost/') ); // true

console.log( isLocalhost('http://localhost/') ); // true

console.log( isLocalhost('https://127.0.0.1/') ); // true

console.log( isLocalhost('mebee.info') ); // false

console.log( isLocalhost('ftp://localhost') ); // false

indexOf

「indexOf」を使用して判定することも可能です。

return url.indexOf('localhost') !== -1 || url.indexOf('127.0.0.1') !== -1 ;

パフォーマンスは、ほぼ同じです。

注意

ただし、上記の方法だと、以下のパターンが「true」と判定されます。

console.log( isLocalhost('http://aaalocalhost/') ); // true

console.log( isLocalhost('http://localhostbbb/') ); // true

console.log( isLocalhost('https://127.0.0.100/') ); // true

「parser」を使用して、URLを分解して「hostname」で判定することで上記は「false」と判定することができます。

const pattern = new RegExp('^(https?:\\/\\/)?'+
  '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.?)+[a-z]{2,}|'+
  '((\\d{1,3}\\.){3}\\d{1,3}))'+
  '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+
  '(\\?[;&a-z\\d%_.~+=-]*)?'+
  '(\\#[-a-z\\d_]*)?$','i');

function isLocalhost(url) {

    if(!pattern.test(url)) return false; // URLであるかのCHECK

    let parser = document.createElement('a');

    parser.href = url;

    return parser.hostname === 'localhost' || parser.hostname === '127.0.0.1';

}


console.log( isLocalhost('https://localhost/') ); // true

console.log( isLocalhost('http://localhost/') ); // true

console.log( isLocalhost('https://127.0.0.1/') ); // true

console.log( isLocalhost('https://mebee.info') ); // false

console.log( isLocalhost('ftp://localhost') ); // false

console.log( isLocalhost('http://aaalocalhost/') ); // false

console.log( isLocalhost('http://localhostbbb/') ); // false

console.log( isLocalhost('https://127.0.0.100/') ); // false

サンプルコード

以下は、
「判定」ボタンをクリックすると、フォームに入力されてURLが「lacalhost」であるかを判定して表示する
サンプルコードとなります。

※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-25" style="margin-top:150px">

    <h2><span class="badge badge-info">結果</span></h2>

    <input id="txt" type="text" class="form-control" />

    <button id="btn" type="button" class="btn mt-1 btn-info">
      判定
    </button>

  </div>

  <script>

    const pattern = new RegExp('^(https?:\\/\\/)?' +
      '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.?)+[a-z]{2,}|' +
      '((\\d{1,3}\\.){3}\\d{1,3}))' +
      '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*' +
      '(\\?[;&a-z\\d%_.~+=-]*)?' +
      '(\\#[-a-z\\d_]*)?$', 'i');

    const isLocalhost = (url) => {

      if (!pattern.test(url)) return false; // URLであるかのCHECK

      let parser = document.createElement('a');

      parser.href = url;

      return parser.hostname === 'localhost' || parser.hostname === '127.0.0.1';

    }

    const hoge = () => {

      document.getElementsByClassName('badge')[0].textContent = isLocalhost(txt.value);

    }

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

  </script>
</body>

</html>

判定されていることが確認できます。