如何在JavaScript中检查空/未定义/空字符串?

JavaScript

梅猿

2020-03-09

我看到了这个问题,但是没有看到JavaScript特定的示例。string.EmptyJavaScript中是否有一个简单的可用工具,还是仅用于检查的情况""

第171篇《如何在JavaScript中检查空/未定义/空字符串?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

23个回答
Gil十三 2020.03.09

我在这里看不到好的答案(至少不是适合我的答案)

因此,我决定回答自己:

value === undefined || value === null || value === "";

您需要开始检查它是​​否未定义。否则,您的方法可能会爆炸,然后可以检查它是否等于null或等于空字符串。

你不能拥有!或仅if(value)当您选中0该选项后才会给出错误答案(0为错误)。

话虽如此,将其包装为以下方法:

public static isEmpty(value: any): boolean { return value === undefined || value === null || value === ""; }

PS .:您不需要检查typeof,因为它甚至在进入方法之前都会爆炸并抛出。

小宇宙神无 2020.03.09

我结合使用,最快的检查是第一位的。

function isBlank(pString) {
    if (!pString || pString.length == 0) {
        return true;
    }
    // Checks for a non-white space character
    // which I think [citation needed] is faster
    // than removing all the whitespace and checking
    // against an empty string
    return !/[^\s]+/.test(pString);
}
小哥Pro梅 2020.03.09

忽略空格字符串,可以使用它来检查null,空和未定义:

var obj = {};
(!!obj.str) // Returns false

obj.str = "";
(!!obj.str) // Returns false

obj.str = null;
(!!obj.str) // Returns false

简洁明了,它适用于未定义的属性,尽管它不是最易读的。

西门逆天 2020.03.09

要检查它是否完全是一个空字符串:

if(val==="")...

要检查它是一个空字符串还是一个无值的逻辑等效项(null,undefined,0,NaN,false,...):

if(!val)...
古一L 2020.03.09

尝试这个:

export const isEmpty = string => (!string || !string.length);
十三西里GO 2020.03.09

尝试这个

str.value.length == 0
Gil伽罗小宇宙 2020.03.09

如果不仅需要检测空字符串,还需要检测空白字符串,我将在Goral的答案中添加:

function isEmpty(s){
    return !s.length;    
}

function isBlank(s){
    return isEmpty(s.trim());    
}
Tony阳光 2020.03.09

到目前为止,还没有像string.empty这样的直接方法来检查字符串是否为空。但是在您的代码中,您可以使用包装检查是否为空字符串,例如:

// considering the variable in which your string is saved is named str.

if (str && str.length>0) { 

  // Your code here which you want to run if the string is not empty.

}

使用此方法,您还可以确保字符串也未定义或为null。请记住,未定义,null和empty是三件事。

阳光神乐 2020.03.09

所有这些答案都很好。

但是我不能确定变量是一个字符串,不只包含空格(这对我很重要),并且可以包含“ 0”(字符串)。

我的版本:

function empty(str){
    return !str || !/[^\s]+/.test(str);
}

empty(null); // true
empty(0); // true
empty(7); // false
empty(""); // true
empty("0"); // false
empty("  "); // true

jsfiddle示例

逆天猿理查德 2020.03.09

我没有注意到一个考虑到字符串中可能存在空字符的答案。例如,如果我们有一个空字符串:

var y = "\0"; // an empty string, but has a null character
(y === "") // false, testing against an empty string does not work
(y.length === 0) // false
(y) // true, this is also not expected
(y.match(/^[\s]*$/)) // false, again not wanted

要测试其无效性,可以执行以下操作:

String.prototype.isNull = function(){ 
  return Boolean(this.match(/^[\0]*$/)); 
}
...
"\0".isNull() // true

它适用于空字符串和空字符串,并且所有字符串均可访问。另外,它可以扩展为包含其他JavaScript空字符或空格字符(即,不间断空格,字节顺序标记,行/段落分隔符等)。

EvaPro 2020.03.09

另外,如果您将填充空格的字符串视为“空”。

您可以使用以下正则表达式对其进行测试:

!/\S/.test(string); // Returns true if blank.
null 2020.03.09

我通常用这样的东西

if (!str.length) {
    // Do something
}
Davaid古一 2020.03.09

我不会太担心最有效的方法。使用最清楚您意图的内容。对我来说通常是strVar == ""

根据康斯坦丁(Constantin)的评论,如果strVar最终可以包含一个整数0值,那么这确实是意图明确的情况之一。

米亚神无 2020.03.09

您还可以使用正则表达式:

if((/^\s*$/).test(str)) { }

检查是否为空或用空格填充的字符串。

YOC40565407 2020.03.09
  1. 检查是否var a;存在
  2. 修剪false spaces值,然后测试emptiness

    if ((a)&&(a.trim()!=''))
    {
      // if variable a is not empty do this 
    }
    
Davaid飞羽 2020.03.09

尝试:

if (str && str.trim().length) {  
    //...
}
Tony西门古一 2020.03.09
var s; // undefined
var s = ""; // ""
s.length // 0

JavaScript中没有任何内容代表空字符串。对照length(如果您知道var永远是字串)或对照""

仲羽蛋蛋 2020.03.09

您可以使用lodash:_.isEmpty(value)。

它涵盖了很多类似的情况下{}''nullundefined,等。

但它总是返回trueNumber类型的JavaScript的基本数据类型一样_.isEmpty(10)或者_.isEmpty(Number.MAX_VALUE)两者的回报true

十三SamJim 2020.03.09

我用:

function empty(e) {
  switch (e) {
    case "":
    case 0:
    case "0":
    case null:
    case false:
    case typeof(e) == "undefined":
      return true;
    default:
      return false;
  }
}

empty(null) // true
empty(0) // true
empty(7) // false
empty("") // true
empty((function() {
    return ""
})) // false
蛋蛋LEY 2020.03.09

如果您需要确保字符串不只是一堆空白(我假设这是用于表单验证),则需要对这些空格进行替换。

if(str.replace(/\s/g,"") == ""){
}
Stafan卡卡西 2020.03.09

您可以得到的最接近的结果str.Empty(以str为字符串为前提)是:

if (!str.length) { ...
JinJin理查德 2020.03.09

先前的所有答案都不错,但这会更好。使用!!不是)运算符。

if(!!str){
    // Some code here
}

或使用类型转换:

if(Boolean(str)){
    // Code here
}

两者执行相同的功能。将变量类型转换为布尔值,其中str是变量。
它返回falsenull,undefined,0,000,"",false
返回true字符串“ 0”和空格“”。

JinJin伽罗小胖 2020.03.09

为了检查字符串是否为空,空或未定义,我使用:

function isEmpty(str) {
    return (!str || 0 === str.length);
}

为了检查字符串是否为空,空或未定义,我使用:

function isBlank(str) {
    return (!str || /^\s*$/.test(str));
}

用于检查字符串是否为空白或仅包含空格:

String.prototype.isEmpty = function() {
    return (this.length === 0 || !this.trim());
};

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android