代码之家  ›  专栏  ›  技术社区  ›  casademora

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

  •  2334
  • casademora  · 技术社区  · 16 年前

    我看到 this question ,但我没有看到特定于JavaScript的示例。有简单的方法吗 string.Empty "" ?

    39 回复  |  直到 5 年前
        1
  •  4250
  •   Flimm D. Ben Knoble    3 年前

    如果你只是想看看是否有 truthy value ,你可以:

    if (strValue) {
        //do something
    }
    

    如果您需要专门检查null上的空字符串,我会考虑根据 "" 是您的最佳选择,使用 the === operator (这样你就知道它实际上是一个你正在比较的字符串)。

    if (strValue === "") {
        //...
    }
    
        2
  •  1316
  •   Flimm D. Ben Knoble    3 年前

    falsey 或者,如果它的length属性等于零(对于字符串,这意味着它是空的),我使用:

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

    (请注意,字符串不是唯一具有 length 属性,例如,数组也有它们。)

    为了检查变量是否为false或字符串是否仅包含空格或为空,我使用:

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

    如果你愿意,你可以 monkey-patch 这个 String

    String.prototype.isEmpty = function() {
        // This doesn't work the same way as the isEmpty function used 
        // in the first example, it will return true for strings containing only whitespace
        return (this.length === 0 || !this.trim());
    };
    console.log("example".isEmpty());
    

    请注意,猴子修补内置类型是有争议的,因为无论出于何种原因,它都可能破坏依赖于现有内置类型结构的代码。

        3
  •  448
  •   Flimm D. Ben Knoble    3 年前

    !! ):

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

    或使用类型转换:

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

    两者的功能相同。将变量类型转换为布尔值,其中 str 是一个变量。

    • 它回来了 false 对于 null , undefined , 0 , 000 , "" , .

    • 它回来了 true 对于除空字符串以外的所有字符串值(包括以下字符串): "0" " "

        4
  •  125
  •   Kick Buttowski    6 年前

    你能找到的最接近的东西 str.Empty (前提是str是字符串)是:

    if (!str.length) { ...
    
        5
  •  111
  •   Sugendran    16 年前

    如果您需要确保字符串不仅仅是一堆空的空格(我假设这是为了表单验证),那么您需要对空格进行替换。

    if(str.replace(/\s/g,"") == ""){
    }
    
        6
  •  70
  •   Peter Mortensen icecrime    5 年前

    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
    
        7
  •  55
  •   Peter Mortensen icecrime    5 年前

    你可以用 lodash : _.isEmpty(值)。

    {} '' , null , undefined

    true 对于 Number JavaScript primitive data types 喜欢 _.isEmpty(10) _.isEmpty(Number.MAX_VALUE) 双方都返回 符合事实的 .

        8
  •  53
  •   Kamil Kiełczewski    5 年前

    表演

    macOS v10.13.6 (High Sierra)针对18种选定的解决方案。解决方案的工作原理稍有不同(对于角落案例输入数据),如下面的代码片段所示。

    • !str == , === length
    • 基于正则表达式的求解( test , replace charAt 对于所有浏览器(H、L、M、P)都是最慢的
    • 标记为“最快”的解决方案仅在一次测试运行中最快,但在许多运行中,它在“快速”解决方案组中发生变化

    Enter image description here

    细节

    • "" "a" " " -空字符串、带字母的字符串和带空格的字符串
    • [] {} f -数组、对象和函数
    • 0 1 NaN Infinity -数字
    • true false -布尔值
    • null undefined

    function A(str) {
      let r=1;
      if (!str)
        r=0;
      return r;
    }
    
    function B(str) {
      let r=1;
      if (str == "")
        r=0;
      return r;
    }
    
    function C(str) {
      let r=1;
      if (str === "")
        r=0;
      return r;
    }
    
    function D(str) {
      let r=1;
      if(!str || 0 === str.length)
        r=0;
      return r;
    }
    
    function E(str) {
      let r=1;
      if(!str || /^\s*$/.test(str))
        r=0;
      return r;
    }
    
    function F(str) {
      let r=1;
      if(!Boolean(str))
        r=0;
      return r;
    }
    
    function G(str) {
      let r=1;
      if(! ((typeof str != 'undefined') && str) )
        r=0;
      return r;
    }
    
    function H(str) {
      let r=1;
      if(!/\S/.test(str))
        r=0;
      return r;
    }
    
    function I(str) {
      let r=1;
      if (!str.length)
        r=0;
      return r;
    }
    
    function J(str) {
      let r=1;
      if(str.length <= 0)
        r=0;
      return r;
    }
    
    function K(str) {
      let r=1;
      if(str.length === 0 || !str.trim())
        r=0;
      return r;
    }
    
    function L(str) {
      let r=1;
      if ( str.replace(/\s/g,"") == "")
        r=0;
      return r;
    }
    
    function M(str) {
      let r=1;
      if((/^\s*$/).test(str))
        r=0;
      return r;
    }
    
    
    function N(str) {
      let r=1;
      if(!str || !str.trim().length)
        r=0;
      return r;
    }
    
    function O(str) {
      let r=1;
      if(!str || !str.trim())
        r=0;
      return r;
    }
    
    function P(str) {
      let r=1;
      if(!str.charAt(0))
        r=0;
      return r;
    }
    
    function Q(str) {
      let r=1;
      if(!str || (str.trim()==''))
        r=0;
      return r;
    }
    
    function R(str) {
      let r=1;
      if (typeof str == 'undefined' ||
          !str ||
          str.length === 0 ||
          str === "" ||
          !/[^\s]/.test(str) ||
          /^\s*$/.test(str) ||
          str.replace(/\s/g,"") === "")
    
        r=0;
      return r;
    }
    
    
    
    
    // --- TEST ---
    
    console.log(                  '   ""  "a"  " " [] {} 0 1 NaN Infinity f true false null undefined ');
    let log1 = (s,f)=> console.log(`${s}: ${f("")}   ${f("a")}    ${f(" ")}   ${f([])}  ${f({})}  ${f(0)} ${f(1)} ${f(NaN)}   ${f(Infinity)}        ${f(f)} ${f(true)}    ${f(false)}     ${f(null)}    ${f(undefined)}`);
    let log2 = (s,f)=> console.log(`${s}: ${f("")}   ${f("a")}    ${f(" ")}   ${f([])}  ${f({})}  ${f(0)} ${f(1)} ${f(NaN)}   ${f(Infinity)}        ${f(f)} ${f(true)}    ${f(false)}`);
    let log3 = (s,f)=> console.log(`${s}: ${f("")}   ${f("a")}    ${f(" ")}`);
    
    log1('A', A);
    log1('B', B);
    log1('C', C);
    log1('D', D);
    log1('E', E);
    log1('F', F);
    log1('G', G);
    log1('H', H);
    
    log2('I', I);
    log2('J', J);
    
    log3('K', K);
    log3('L', L);
    log3('M', M);
    log3('N', N);
    log3('O', O);
    log3('P', P);
    log3('Q', Q);
    log3('R', R);

    然后对所有方法执行速度测试用例 str = "" 对于浏览器ChromeV78.0.0、SafariV13.0.4和FirefoxV71.0.0,您可以在您的机器上运行测试 here

    Enter image description here

        9
  •  42
  •   T.Todua Laurent W.    4 年前

    非常通用的“一体式”功能( 但不推荐

    function is_empty(x)
    {
        return (                                                           //don't put newline after return
            (typeof x == 'undefined')
                  ||
            (x == null)
                  ||
            (x == false)        //same as: !x
                  ||
            (x.length == 0)
                  ||
            (x == 0)            // note this line, you might not need this. 
                  ||
            (x == "")
                  ||
            (x.replace(/\s/g,"") == "")
                  ||
            (!/[^\s]/.test(x))
                  ||
            (/^\s*$/.test(x))
        );
    }
    

    但是,我不建议使用它,因为您的目标变量应该是特定类型(即字符串、数字或对象?),所以应用与该变量相关的检查。

        10
  •  38
  •   cllpse    16 年前
    var s; // undefined
    var s = ""; // ""
    s.length // 0
    

    JavaScript中没有表示空字符串的内容。对其中一个进行检查 length (如果您知道var将始终是一个字符串)或 ""

        11
  •  37
  •   afuzzyllama user7757658    12 年前

    if (str && str.trim().length) {  
        //...
    }
    
        12
  •  31
  •   Peter Mortensen icecrime    5 年前

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

    Constantin ,如果strVar可能最终包含一个0整数值,那么这确实是一种澄清意图的情况。

        13
  •  21
  •   Peter Mortensen icecrime    5 年前

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

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

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

        14
  •  21
  •   Praveen M P    4 年前

    毫无疑问,对于快速简单的实施,赢家是: if (!str.length) {...}

    function empty(str)
    {
        if (typeof str == 'undefined' || !str || str.length === 0 || str === "" || !/[^\s]/.test(str) || /^\s*$/.test(str) || str.replace(/\s/g,"") === "")
            return true;
        else
            return false;
    }

    我知道有点过分。

        15
  •  20
  •   Kruti Patel Suresh Atta    8 年前
    1. var a; 存在
    2. 修剪 false spaces 在值中,然后测试 emptiness

      if ((a)&&(a.trim()!=''))
      {
        // if variable a is not empty do this 
      }
      
        16
  •  17
  •   Peter Mortensen icecrime    5 年前

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

    !/\S/.test(string); // Returns true if blank.
    
        17
  •  17
  •   Peter Mortensen icecrime    5 年前

    我通常用这样的东西,

    if (!str.length) {
        // Do something
    }
    
        18
  •  13
  •   Josef.B    10 年前

    function isEmpty(s){
        return !s.length;    
    }
    
    function isBlank(s){
        return isEmpty(s.trim());    
    }
    
        19
  •  13
  •   Peter Mortensen icecrime    5 年前

    首先是:

    return (!value || value == undefined || value == "" || value.length == 0);
    

    是0。因此,放下它:

    return (!value || value == undefined || value == "");
    

    return (!value || value == undefined);
    

    和undefined为true,因此不需要检查。因此,我们:

    return (!value);
    

    我们不需要括号:

    return !value
    
        20
  •  13
  •   Will    3 年前

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

    function isBlank(pString) {
        if (!pString) {
            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);
    }
    
        21
  •  11
  •   Bikush    12 年前

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

    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空字符或空白字符(即不间断空格、字节顺序标记、行/段分隔符等)。

        22
  •  11
  •   Imran Ahmad    7 年前

    . 所以我写了这个。

    var isEmpty = function(data) {
        if(typeof(data) === 'object'){
            if(JSON.stringify(data) === '{}' || JSON.stringify(data) === '[]'){
                return true;
            }else if(!data){
                return true;
            }
            return false;
        }else if(typeof(data) === 'string'){
            if(!data.trim()){
                return true;
            }
            return false;
        }else if(typeof(data) === 'undefined'){
            return true;
        }else{
            return false;
        }
    }
    

    用例和结果。

    console.log(isEmpty()); // true
    console.log(isEmpty(null)); // true
    console.log(isEmpty('')); // true
    console.log(isEmpty('  ')); // true
    console.log(isEmpty(undefined)); // true
    console.log(isEmpty({})); // true
    console.log(isEmpty([])); // true
    console.log(isEmpty(0)); // false
    console.log(isEmpty('Hey')); // false
    
        23
  •  11
  •   Harshit Agarwal    5 年前

    // 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.
    
    }
    

    使用此选项还可以确保字符串不是未定义的或也不是空的。记住,undefined、null和empty是三个不同的东西。

        24
  •  11
  •   Peter Mortensen icecrime    5 年前

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

    所以我决定回答自己:

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

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

    你不可能有!!或者仅仅 if(value) 如果你查一下 0 它会给你一个错误的答案(0是错误的)。

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

    附言: 你不需要检查类型 ,因为它甚至在进入方法之前就会爆炸并抛出

        25
  •  10
  •   Peter Mortensen icecrime    5 年前

    所有这些答案都很好。

    但我不能确定变量是否是字符串,是否只包含空格(这对我很重要),是否可以包含“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 .

        26
  •  10
  •   Peter Mortensen icecrime    5 年前

    我做了一些研究,研究了如果将非字符串和非空/空值传递给tester函数会发生什么。正如许多人所知,(0==“”)在JavaScript中是正确的,但由于0是一个值,并且不是空的或null,您可能需要测试它。

    以下两个函数仅对未定义、null、空/空白值返回true,对其他所有值(如数字、布尔值、对象、表达式等)返回false。

    function IsNullOrEmpty(value)
    {
        return (value == null || value === "");
    }
    function IsNullOrWhiteSpace(value)
    {
        return (value == null || !/\S/.test(value));
    }
    

    存在更复杂的例子,但这些例子很简单,并且给出了一致的结果。不需要测试未定义,因为它包含在(value==null)检查中。你也可以模仿 C#

    String.IsNullOrEmpty = function (value) { ... }
    

    您不希望将其放入Strings原型中,因为如果String类的实例为null,则会出现以下错误:

    String.prototype.IsNullOrEmpty = function (value) { ... }
    var myvar = null;
    if (1 == 2) { myvar = "OK"; } // Could be set
    myvar.IsNullOrEmpty(); // Throws error
    

    我使用以下值数组进行了测试。如果有疑问,可以循环测试函数。

    // Helper items
    var MyClass = function (b) { this.a = "Hello World!"; this.b = b; };
    MyClass.prototype.hello = function () { if (this.b == null) { alert(this.a); } else { alert(this.b); } };
    var z;
    var arr = [
    // 0: Explanation for printing, 1: actual value
        ['undefined', undefined],
        ['(var) z', z],
        ['null', null],
        ['empty', ''],
        ['space', ' '],
        ['tab', '\t'],
        ['newline', '\n'],
        ['carriage return', '\r'],
        ['"\\r\\n"', '\r\n'],
        ['"\\n\\r"', '\n\r'],
        ['" \\t \\n "', ' \t \n '],
        ['" txt \\t test \\n"', ' txt \t test \n'],
        ['"txt"', "txt"],
        ['"undefined"', 'undefined'],
        ['"null"', 'null'],
        ['"0"', '0'],
        ['"1"', '1'],
        ['"1.5"', '1.5'],
        ['"1,5"', '1,5'], // Valid number in some locales, not in JavaScript
        ['comma', ','],
        ['dot', '.'],
        ['".5"', '.5'],
        ['0', 0],
        ['0.0', 0.0],
        ['1', 1],
        ['1.5', 1.5],
        ['NaN', NaN],
        ['/\S/', /\S/],
        ['true', true],
        ['false', false],
        ['function, returns true', function () { return true; } ],
        ['function, returns false', function () { return false; } ],
        ['function, returns null', function () { return null; } ],
        ['function, returns string', function () { return "test"; } ],
        ['function, returns undefined', function () { } ],
        ['MyClass', MyClass],
        ['new MyClass', new MyClass()],
        ['empty object', {}],
        ['non-empty object', { a: "a", match: "bogus", test: "bogus"}],
        ['object with toString: string', { a: "a", match: "bogus", test: "bogus", toString: function () { return "test"; } }],
        ['object with toString: null', { a: "a", match: "bogus", test: "bogus", toString: function () { return null; } }]
    ];
    
        27
  •  10
  •   Peter Mortensen icecrime    5 年前

    要检查它是否完全是空字符串,请执行以下操作:

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

    if(!val)...
    
        28
  •  10
  •   sean    4 年前

    使用空合并运算符修剪空白:

    if (!str?.trim()) {
      // do something...
    }
    
        29
  •  10
  •   Ibrahim shamma    4 年前

    如果只是简单地检查空字符串

    if (str.length){
      //do something
    }
    

    如果您还想包括null&你的支票没有定义

    if (Boolean(str)){
      //this will be true when the str is not empty nor null nor undefined
    }
    
        30
  •  9
  •   Agustí Sánchez    8 年前

    isEmpty() 方法,则必须检查类型和长度:

    if (typeof test === 'string' && test.length === 0){
      ...
    

    需要进行类型检查,以避免出现运行时错误 test undefined null