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

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

    Meanwhile we can have one function that checks for all 'empties' like null, undefined, '', ' ', {}, []. So I just wrote this.

    var isEmpty = function(data) {
        if(typeof(data) === 'object'){
            if(JSON.stringify(data) === '{}' || JSON.stringify(data) === '[]'){
                return true;
            }else if(!data){
                return true;
            }
            return false;
        }else if(typeof(data) === 'string'){
            if(!data.trim()){
                return true;
            }
            return false;
        }else if(typeof(data) === 'undefined'){
            return true;
        }else{
            return false;
        }
    }
    

    Use cases and results.

    console.log(isEmpty()); // true
    console.log(isEmpty(null)); // true
    console.log(isEmpty('')); // true
    console.log(isEmpty('  ')); // true
    console.log(isEmpty(undefined)); // true
    console.log(isEmpty({})); // true
    console.log(isEmpty([])); // true
    console.log(isEmpty(0)); // false
    console.log(isEmpty('Hey')); // false
    

提交回复
热议问题