JavaScript中是否存在字符串.Empty,还是只是检查“”?


当前回答

var s; // undefined
var s = ""; // ""
s.length // 0

JavaScript中没有表示空字符串的内容。检查长度(如果您知道var始终是字符串)或“”

其他回答

嗯,检查这个的最简单的函数是。。。

const checkEmpty=string=>(strim.trim()==“”)||!strim.trim();

用法:

checkEmpty(""); // returns true.
checkEmpty("mystr"); // returns false.

就是这么简单。:)

同时,我们可以有一个函数来检查所有“空”,如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;
    }
}

用例和结果。

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

最接近str.Empty(前提是str是String)的是:

if (!str.length) { ...

您可以使用typeof运算符和length方法检查这一点。

const isNonEmptyString = (value) => typeof(value) == 'string' && value.length > 0
function tell()
{
    var pass = document.getElementById('pasword').value;
    var plen = pass.length;

    // Now you can check if your string is empty as like
    if(plen==0)
    {
        alert('empty');
    }
    else
    {
        alert('you entered something');
    }
}

<input type='text' id='pasword' />

这也是检查字段是否为空的通用方法。