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

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

    The closest thing you can get to str.Empty (with the precondition that str is a String) is:

    if (!str.length) { ...
    
    0 讨论(0)
  • 2020-11-22 00:05

    You could also go with regular expressions:

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

    Checks for strings that are either empty or filled with whitespace.

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

    Very generic "All-In-One" Function (not recommended though):

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

    However, I don't recommend to use that, because your target variable should be of specific type (i.e. string, or numeric, or object?), so apply the checks that are relative to that variable.

    0 讨论(0)
  • 2020-11-22 00:10
    var s; // undefined
    var s = ""; // ""
    s.length // 0
    

    There's nothing representing an empty string in JavaScript. Do a check against either length (if you know that the var will always be a string) or against ""

    0 讨论(0)
  • 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.

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

    I would not worry too much about the most efficient method. Use what is most clear to your intention. For me that's usually strVar == "".

    As per the comment from Constantin, if strVar could some how end up containing an integer 0 value, then that would indeed be one of those intention-clarifying situations.

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