How can I check for an empty/undefined/null string in JavaScript?

后端 未结 30 4047
长发绾君心
长发绾君心 2020-11-21 23:47

I saw this question, but I didn\'t see a JavaScript specific example. Is there a simple string.Empty available in JavaScript, or is it just a case of checking f

相关标签:
30条回答
  • 2020-11-22 00:19

    If one needs to detect not only empty but also blank strings, I'll add to Goral's answer:

    function isEmpty(s){
        return !s.length;    
    }
    
    function isBlank(s){
        return isEmpty(s.trim());    
    }
    
    0 讨论(0)
  • 2020-11-22 00:20
    1. check that var a; exist
    2. trim out the false spaces in the value, then test for emptiness

      if ((a)&&(a.trim()!=''))
      {
        // if variable a is not empty do this 
      }
      
    0 讨论(0)
  • 2020-11-22 00:20

    You can easily add it to native String object in JavaScript and reuse it over and over...
    Something simple like below code can do the job for you if you want to check '' empty strings:

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

    Otherwise if you'd like to check both '' empty string and ' ' with space, you can do that by just adding trim(), something like the code below:

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

    and you can call it this way:

    ''.isEmpty(); //return true
    'alireza'.isEmpty(); //return false
    
    0 讨论(0)
  • 2020-11-22 00:22

    You can use lodash: _.isEmpty(value).

    It covers a lot of cases like {}, '', null, undefined, etc.

    But it always returns true for Number type of JavaScript primitive data types like _.isEmpty(10) or _.isEmpty(Number.MAX_VALUE) both returns true.

    0 讨论(0)
  • 2020-11-22 00:22

    Also, in case you consider a whitespace filled string as "empty".

    You can test it with this regular expression:

    !/\S/.test(string); // Returns true if blank.
    
    0 讨论(0)
  • 2020-11-22 00:22

    There's no isEmpty() method, you have to check for the type and the length:

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

    The type check is needed in order to avoid runtime errors when test is undefined or null.

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