What is the best way to test for an empty string with jquery-out-of-the-box?

后端 未结 10 813
Happy的楠姐
Happy的楠姐 2020-11-29 15:45

What is the best way to test for an empty string with jquery-out-of-the-box, i.e. without plugins? I tried this.

But it did\'t work at least out-of-the-box. It woul

相关标签:
10条回答
  • 2020-11-29 16:07

    To checks for all 'empties' like null, undefined, '', ' ', {}, [].

    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;
        }
    }
    

    Use cases and results.

    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
    
    0 讨论(0)
  • 2020-11-29 16:10

    Since you can also input numbers as well as fixed type strings, the answer should actually be:

    function isBlank(value) {
      return $.trim(value);
    }
    
    0 讨论(0)
  • 2020-11-29 16:11
    if((a.trim()=="")||(a=="")||(a==null))
    {
        //empty condition
    }
    else
    {
        //working condition
    }
    
    0 讨论(0)
  • 2020-11-29 16:13

    Check if data is a empty string (and ignore any white space) with jQuery:

    function isBlank( data ) {
        return ( $.trim(data).length == 0 );
    }
    
    0 讨论(0)
  • 2020-11-29 16:14

    Try this

    if(!a || a.length === 0)
    
    0 讨论(0)
  • 2020-11-29 16:16

    The link you gave seems to be attempting something different to the test you are trying to avoid repeating.

    if (a == null || a=='')
    

    tests if the string is an empty string or null. The article you linked to tests if the string consists entirely of whitespace (or is empty).

    The test you described can be replaced by:

    if (!a)
    

    Because in javascript, an empty string, and null, both evaluate to false in a boolean context.

    0 讨论(0)
提交回复
热议问题