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


当前回答

检查是否为空:

var str = "Hello World!";
if(str === ''){alert("THE string str is EMPTY");}

要检查它是否为string类型,请执行以下操作:

var str = "Hello World!";
if(typeof(str) === 'string'){alert("This is a String");}

其他回答

这里有很多有用的信息,但在我看来,其中一个最重要的因素没有得到解决。

null、undefined和“”都是假的。

当计算空字符串时,通常是因为需要用其他东西替换它。

在这种情况下,您可以预期以下行为。

var a = ""
var b = null
var c = undefined

console.log(a || "falsy string provided") // prints ->"falsy string provided"
console.log(b || "falsy string provided") // prints ->"falsy string provided"
console.log(c || "falsy string provided") // prints ->"falsy string provided"

考虑到这一点,可以返回字符串是否为“”、null或undefined(无效字符串)与有效字符串的方法或函数如下所示:

const validStr = (str) => str ? true : false

validStr(undefined) // returns false
validStr(null) // returns false
validStr("") // returns false
validStr("My String") // returns true

我没有注意到一个考虑到字符串中可能存在空字符的答案。例如,如果我们有一个空字符串:

var y = "\0"; // an empty string, but has a null character
(y === "") // false, testing against an empty string does not work
(y.length === 0) // false
(y) // true, this is also not expected
(y.match(/^[\s]*$/)) // false, again not wanted

要测试其空性,可以执行以下操作:

String.prototype.isNull = function(){ 
  return Boolean(this.match(/^[\0]*$/)); 
}
...
"\0".isNull() // true

它在空字符串和空字符串上工作,所有字符串都可以访问它。此外,它还可以扩展为包含其他JavaScript空字符或空白字符(即非分隔空格、字节顺序标记、行/段落分隔符等)。

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

const isNonEmptyString = (value) => typeof(value) == 'string' && value.length > 0

我通常使用以下内容:

if (str == "") {
     //Do Something
}
else {
     //Do Something Else
}
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' />

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