javascript includesで大文字・小文字を区別せずに文字列に指定した文字列が含まれているかを判定する

javascript includesで大文字・小文字を区別せずに文字列に指定した文字列が含まれているかを判定する

javascriptで、includesで大文字・小文字を区別せずに文字列に指定した文字列が含まれているかを判定するサンプルコードを記述してます。

環境

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

大文字・小文字を区別せずに判定

大文字・小文字を区別せずに判定するには、双方を小文字か大文字に変換してから比較します。

console.log( "AbcDe".toLowerCase().includes("bc".toLowerCase()) ); // true
console.log( "AbcDe".toUpperCase().includes("bc".toUpperCase()) ); // true

console.log( "AbcDe".toLowerCase().includes("DE".toLowerCase()) ); // true
console.log( "AbcDe".toUpperCase().includes("DE".toUpperCase()) ); // true

console.log( "AbcDe".toLowerCase().includes("EF".toLowerCase()) ); // false
console.log( "AbcDe".toUpperCase().includes("EF".toUpperCase()) ); // false

実行結果

全角のアルファベットにも使用可能です。

console.log( "ABc".toLowerCase().includes("ab".toLowerCase()) ); // true
console.log( "ABc".toUpperCase().includes("ab".toUpperCase()) ); // true

サンプルコード

以下は、テキストフォームに入力された2つの文字列を大文字・小文字を区別せずに比較した結果表示するだけのサンプルコードとなります。

※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 id="foo" class="container text-center w-25" style="margin-top:150px">

    <h2><span id="result" class="badge badge-success">実行結果</span></h2>

    <input id="txt1" type="text" class="form-control" placeholder="判定する文字列"/>
    <input id="txt2" type="text" class="form-control" placeholder="検索する文字列" />

    <button id="btn" type="button" class="btn btn-success btn-rounded mt-1">
      実行
    </button>

  </div>

  <script>    

    btn.onclick = () => {      

      txt1.value.toLowerCase().includes(txt2.value.toLowerCase()) ? result.textContent = '含まれてます' : result.textContent = '含まれてません' ;

    }
    
  </script>
</body>

</html>

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