How to check if a variable is null or empty string or all whitespace in JavaScript?

后端 未结 12 1340
失恋的感觉
失恋的感觉 2020-12-23 13:05

I need to check to see if a variable is null or has all empty spaces or is just blank (\"\").

I have the following, but it is not working:

var addr;
         


        
相关标签:
12条回答
  • 2020-12-23 13:25

    You can create your own method Equivalent to

    String.IsNullOrWhiteSpace(value)

    function IsNullOrWhiteSpace( value) {
    
        if (value== null) return true;
    
        return value.replace(/\s/g, '').length == 0;
    }
    
    0 讨论(0)
  • 2020-12-23 13:26
    if (addr == null || addr.trim() === ''){
      //...
    }
    

    A null comparison will also catch undefined. If you want false to pass too, use !addr. For backwards browser compatibility swap addr.trim() for $.trim(addr).

    0 讨论(0)
  • 2020-12-23 13:26

    Try this out

    /**
      * Checks the string if undefined, null, not typeof string, empty or space(s)
      * @param {any} str string to be evaluated
      * @returns {boolean} the evaluated result
    */
    function isStringNullOrWhiteSpace(str) {
        return str === undefined || str === null
                                 || typeof str !== 'string'
                                 || str.match(/^ *$/) !== null;
    }
    

    You can use it like this

    isStringNullOrWhiteSpace('Your String');
    
    0 讨论(0)
  • 2020-12-23 13:26
    function isEmptyOrSpaces(str){
        return str === null || str.match(/^[\s\n\r]*$/) !== null;
    }
    
    0 讨论(0)
  • 2020-12-23 13:28

    A non-jQuery solution that more closely mimics IsNullOrWhiteSpace, but to detect null, empty or all-spaces only:

    function isEmptyOrSpaces(str){
        return str === null || str.match(/^ *$/) !== null;
    }
    

    ...then:

    var addr = '  ';
    
    if(isEmptyOrSpaces(addr)){
        // error 
    }
    

    * EDIT * Please note that op specifically states:

    I need to check to see if a var is null or has any empty spaces or for that matter just blank.

    So while yes, "white space" encompasses more than null, spaces or blank my answer is intended to answer op's specific question. This is important because op may NOT want to catch things like tabs, for example.

    0 讨论(0)
  • 2020-12-23 13:33
    isEmptyOrSpaces(str){
        return !str || str.trim() === '';
    }
    
    0 讨论(0)
提交回复
热议问题