javascript 空文字であるかを判定する

javascript 空文字であるかを判定する

javascriptで、空文字であるかを判定するサンプルコードを掲載してます。ブラウザはchromeを使用しています。

環境

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

空文字であるかを判定

空文字であるかを判定するには、文字列のサイズを調べることのできる「length」を使用したり、「”」と比較することで可能です。

'use strict';

const str = ''

if (str === '') {
  console.log('空文字です')
}

if (str.length === 0) {
  console.log('空文字です')
}

if (!str) {
  console.log('空文字です')
}

実行結果を確認すると、空文字であることが判定されていることが確認できます。

ただし「null」の場合は「(!str)」は「true」を返します。

const str = null

if (!str) {
  console.log('空文字です')
}

サンプルコード

以下は、
「実行」ボタンをクリックして、空文字を用意して判定した結果を表示するサンプルコードとなります。

※cssには「tailwind」を使用して、アロー関数で関数は定義してます。

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

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet">  
</head>

<script>
  
  const hoge = () => {

    const str = ''

    bar.innerHTML = !str ? '空文字です' : '空文字ではありません'
    
  }

  window.onload = () => {

    btn.onclick = () => { hoge() }

  }

</script>

<body>
  <div class="container mx-auto my-56 w-1/3 px-4">

    <div id="sample" class="flex flex-col justify-center">

      <h1 class="font-semibold text-gray-500 text-lg mr-auto">実行結果</h1>
      <h1 id="bar" class="font-semibold text-gray-500 text-lg mr-auto"></h1>

      <button id="btn"
        class="mb-2 md:mb-0 bg-transparent hover:bg-purple-300 text-purple-700 font-semibold hover:text-white py-2 px-4 border border-purple-300 hover:border-transparent rounded">
        実行
      </button>

    </div>

  </div>
</body>

</html>

実行結果を確認すると、結果が表示されていることが確認できます。