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


当前回答

检查是否为字符串类型,如果不为空:

const isNonEmptyString = (val) => typeof val === 'string' && !!val

其他回答

也可以使用正则表达式:

if((/^\s*$/).test(str)) { }

检查是否有空字符串或空白字符串。

我不会太担心最有效的方法。使用最明确的意图。对我来说,这通常是strVar==“”。

根据Constantin的评论,如果strVar可以包含一个0整数值,那么这确实是一种意图明确的情况。

您可以使用lodash:_.isEmpty(值)。

它涵盖了许多情况,如{}、“”、null、undefined等。

但对于JavaScript原始数据类型的Number类型(如_.isEmpty(10)或_.isEmpty(Number.MAX_VALUE)),它总是返回true。

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' />

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

Try:

if (str && str.trim().length) {  
    //...
}