检测空字符串的 JS函数

在开发 Web 应用程序时,经常需要编写功能来验证和处理用户输入的数据。其中,检查字符串是否为空是一个常见的需求。

1. 编写 isEmpty 函数

首先,我们来编写一个名为 isEmpty 的函数,它将接收一个字符串作为参数,并返回一个布尔值来指示该字符串是否为空。这里我们考虑了空字符串、null、undefined 以及仅包含空白字符的情况。

/**
 * 判断字符串是否为空
 * @param {string} str 待检测的字符串
 * @returns {boolean} 如果字符串为空则返回 true,否则返回 false
 */
export function isEmpty(str) {
  // 检测 null 或者 undefined
  if (str === null || typeof str === 'undefined') {
    return true;
  }
  // 将字符串转换为非空格的字符并判断长度是否为 0
  return str.toString().replace(/(^\s*)|(\s*$)/g, '') === '';
}
2. 使用 isEmpty 函数

接下来,我们将展示如何在实际代码中使用 isEmpty 函数来处理空字符串的情况。

// 导入 isEmpty 函数(假设已经在其他文件中定义)
import { isEmpty } from './utils';

// 示例字符串
let str1 = '';            // 空字符串
let str2 = '   ';         // 仅包含空白字符
let str3 = null;          // null
let str4 = undefined;     // undefined
let str5 = 'Hello, world!'; // 非空字符串

// 使用 isEmpty 函数进行判断
if (isEmpty(str1)) {
  console.log('str1 为空字符串');  // 输出
}

if (isEmpty(str2)) {
  console.log('str2 仅包含空白字符');  // 输出
}

if (isEmpty(str3)) {
  console.log('str3 为 null');  // 输出
}

if (isEmpty(str4)) {
  console.log('str4 为 undefined');  // 输出
}

if (isEmpty(str5)) {
  console.log('str5 是非空字符串');  // 不输出,因为 str5 不为空
}
  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值