gpt4 book ai didi

javascript - 如何检查变量是否为 null 或空字符串或 JavaScript 中的所有空格?

转载 作者:IT王子 更新时间:2023-10-29 02:49:31 25 4
gpt4 key购买 nike

我需要检查一个变量是否为 null 或全部为空白或只是空白 ("")。

我有以下内容,但它不起作用:

var addr;
addr = " ";

if (!addr) {
// pull error
}

如果我执行以下操作,它会起作用:

if (addr) {

}​

我需要的是 C# 方法之类的东西 String.IsNullOrWhiteSpace(value) .

最佳答案

一种非 jQuery 解决方案,更接近地模仿 IsNullOrWhiteSpace,但仅检测 null、空或全空格:

function isEmptyOrSpaces(str){
return str === null || str.match(/^ *$/) !== null;
}

...然后:

var addr = '  ';

if(isEmptyOrSpaces(addr)){
// error
}

* 编辑 *请注意,op 明确指出:

I need to check to see if a var is null or has any empty spaces or for that matter just blank.

因此,虽然是的,但“空白”包含的不仅仅是空值、空格或空白,我的回答旨在回答 op 的具体问题。这很重要,因为 op 可能不想捕获诸如制表符之类的东西。

关于javascript - 如何检查变量是否为 null 或空字符串或 JavaScript 中的所有空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10232366/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com