在 React 中检查字符串是否为空

要检查 React 中的字符串是否为空,请访问其长度属性并检查它是否等于 0,例如 if (str.length === 0) {}。 如果字符串的长度等于 0,则字符串为空,否则不为空。

import {useEffect, useState} from 'react';

export default function App() {
  const [message, setMessage] = useState('');

  useEffect(() => {
    if (typeof message === 'string' && message.length === 0) {
      console.log('string is empty');
    } else {
      console.log('string is NOT empty');
    }

    // ?️ trim leading and trailing whitespace
    if (typeof message === 'string' && message.trim().length === 0) {
      console.log('string is empty');
    } else {
      console.log('string is NOT empty');
    }
  }, [message]);

  return (
    <div>
      <h2>String: {message}</h2>

      <button onClick={() => setMessage('Hello world')}>Set state</button>
    </div>
  );
}

在 React 中检查字符串是否为空

第一个 if 语句检查消息变量是否存储了字符串类型的值并且字符串为空。

如果我们考虑一个只包含空格的空字符串,可以使用 trim() 方法在检查字符串是否为空之前删除任何前导或尾随空格。

const str = '   ';

if (typeof str === 'string' && str.trim().length === 0) {
  console.log('string is empty');
} else {
  console.log('string is NOT empty');
}

trim() 方法从字符串中删除前导和尾随空格。 如果字符串只包含空格,则 trim() 返回一个空字符串。

要检查字符串是否真实且包含一个或多个字符,请将字符串添加到 if 语句中。

const str = 'hello world';

if (str) {
  // 如果此代码块运行
  // ?️ str 不是 "", undefined, null, 0, false, NaN
  console.log('string is truthy');
}

如果 str 变量设置为空字符串undefinednull0false 或 NaN,则 if 块中的代码不会运行。

明确地说,我们可以检查字符串是否等于空字符串。

const str = '';

if (typeof str === 'string' && str !== '') {
  // 如果此代码块运行
  // ?️ 字符串不为空
}

if 语句检查 str 变量是否存储了 string 类型的值,并且其值不等于空字符串。

这种方法不适用于包含空格“”的字符串。 在这种情况下,我们必须在检查字符串是否为空之前去掉空格。

const str = '      ';

if (typeof str === 'string' && str.trim() !== '') {
  // 如果此代码块运行
  // ?️ 字符串不为空
}

trim() 方法删除前导和尾随空格,因此 if 块仅在 str 变量包含至少 1 个字符时运行。