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

后端 未结 12 1339
失恋的感觉
失恋的感觉 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: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');
    

提交回复
热议问题