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

后端 未结 30 4860
长发绾君心
长发绾君心 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: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
    

提交回复
热议问题