What is the best way to test for an empty string with jquery-out-of-the-box?

后端 未结 10 826
Happy的楠姐
Happy的楠姐 2020-11-29 15:45

What is the best way to test for an empty string with jquery-out-of-the-box, i.e. without plugins? I tried this.

But it did\'t work at least out-of-the-box. It woul

10条回答
  •  难免孤独
    2020-11-29 16:07

    To checks for all 'empties' like null, undefined, '', ' ', {}, [].

    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
    

提交回复
热议问题