Javascript:如何检查字符串是否为空?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2381456/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:01:13  来源:igfitidea点击:

Javascript: How to check if a string is empty?

javascriptstring

提问by Andrew

I know this is really basic, but I am new to javascript and can't find an answer anywhere.

我知道这真的很基础,但我是 javascript 新手,在任何地方都找不到答案。

How can I check if a string is empty?

如何检查字符串是否为空?

回答by Dustin Laine

I check length.

我检查长度。

if (str.length == 0) {
}

回答by nxt

If you want to know if it's an empty string use === instead of ==.

如果您想知道它是否为空字符串,请使用 === 而不是 ==。

if(variable === "") {
}

This is because === will only return true if the values on both sides are of the same type, in this case a string.

这是因为 === 只有在双方的值是相同类型时才会返回 true,在这种情况下是一个字符串。

for example: (false == "") will return true, and (false === "") will return false.

例如: (false == "") 将返回 true,而 (false === "") 将返回 false。

回答by Tom Castle

This should work:

这应该有效:

if (variable === "") {

}

回答by Christopher Richa

But for a better check:

但为了更好的检查:

if(str === null || str === '')
{
    //enter code here
}

回答by Ray

if (value == "") {
  // it is empty
}