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

后端 未结 30 4604
长发绾君心
长发绾君心 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条回答
  •  Happy的楠姐
    2020-11-22 00:11

    All these answers are nice.

    But I cannot be sure that variable is a string, doesn't contain only spaces (this is important for me), and can contain '0' (string).

    My version:

    function empty(str){
        return !str || !/[^\s]+/.test(str);
    }
    
    empty(null); // true
    empty(0); // true
    empty(7); // false
    empty(""); // true
    empty("0"); // false
    empty("  "); // true
    

    Sample on jsfiddle.

提交回复
热议问题