[javascript入門] 文字列が空かどうかチェックする方法まとめ

javascriptでの文字列に対する空チェックは、C#やPHPなどと異なり、「undefined」「null」「’ ‘ (空)」など対象がさまざまです。

今回は、文字列の空チェックの方法を、状態含めてまとめておきたいと思います。

\自身のスキルを向上するには技術書で!!/

月額¥980で技術書が読み放題!!

  • ビジネススキルとマインド向上したい!!
  • 決断や行動を先送りにしてしまう方!!

Kindle Unlimitedでは30日間無料体験実施中!登録はこちら!

文字列が「空」であるかどうかを確認

文字列が「空」であるかどうかは「if文」を利用して確認するのがベストです。

function isStringEmpty(str) {
  if (str === '') {
    console.log('String is empty');
  } else {
    console.log('String is NOT empty');
  }
}
const str1 = 'not empty';
const str2 = ''; // empty
const str3 = '   '; // 空白文字列
isStringEmpty(str1); // String is NOT empty
isStringEmpty(str2); // String is empty
isStringEmpty(str3); // String is NOT empty

空白文字列を「空」文字列と判断させたい場合は、trim() を使って空白を削除することで判定することができます。

function isStringEmpty(str) {
  if (str.trim() === '') {
    console.log('String is empty');
  } else {
    console.log('String is NOT empty');
  }
}
const str1 = 'not empty';
const str2 = ''; // empty
const str3 = '   '; // 空白文字列
isStringEmpty(str1); // String is NOT empty
isStringEmpty(str2); // String is empty
isStringEmpty(str3); // String is empty

しかし、これだけだと null や undefinedに対して対応していません。実際に上記の isStringEmpty() で処理すると、「String is NOT empty」が出力されます。

const str4 = undefined; 
const str5 = null; 
isStringEmpty(str4); // String is NOT empty
isStringEmpty(str5); // String is NOT empty

nullやundefinedに対する空文字チェック

nullやundefinedに対応する一番簡単な方法は「Null合体演算子」を利用するする方法です。

function isStringEmpty(str) {
  if (str ?? true) {
    console.log('String is empty');
  } else {
    console.log('String is NOT empty');
  }
}
const str1 = undefined; 
const str2 = null; 
isStringEmpty(str1); // String is empty
isStringEmpty(str2); // String is empty

ただし、これだと「空文字 (”)」には対応しません。

空文字、null、undefinedすべてに対応したチェック方法

すべての値に対して空文字チェックを行う方法は下記の通りです。

function isStringEmpty(str) {
  if (str?.trim()) {
    console.log('String is NOT empty');
  } else {
    console.log('String is empty');
  }
}
const str1 = 'not empty';
const str2 = ''; // empty
const str3 = undefined; 
const str4 = null; 
isStringEmpty(str1); // String is NOT empty
isStringEmpty(str2); // String is empty
isStringEmpty(str3); // String is empty
isStringEmpty(str4); // String is empty

上記のケースでは空白文字列も全て空文字として扱うようになるので、もし空文字として「空白文字」を扱いたくない場合は、シンプルにif文で対応することも可能です。

function isStringEmpty(str) {
  if (str) {
    console.log('String is NOT empty');
  } else {
    console.log('String is empty');
  }
}

const str1 = 'not empty';
const str2 = ''; // empty
const str3 = undefined; 
const str4 = null; 
const str5 = '   '; // 空白文字列
isStringEmpty(str1); // String is NOT empty
isStringEmpty(str2); // String is empty
isStringEmpty(str3); // String is empty
isStringEmpty(str4); // String is empty
isStringEmpty(str5); // String is NOT empty

上記のようにただif文を利用するだけであれば、空白文字列は「文字列」として扱いそれ以外の場合は「空文字」として扱います。

最後に

javascriptでの空文字判定は結構よく使われます。
是非覚えておきましょう。

タイトルとURLをコピーしました