如何使用 JavaScript 测试空字符串/null?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5746629/
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 18:40:02  来源:igfitidea点击:

How do I test for a empty string/null, using JavaScript?

javascriptjquery

提问by Nasir

How do I test for a input[text] field that has nothing in?

如何测试没有任何内容的 input[text] 字段?

This is what I have so far:

这是我到目前为止:

    if ($('#StartingPrice').length == ""){
        alert("ERROR!");
    }

Any help would be greatly appreciated, Thanks

任何帮助将不胜感激,谢谢

回答by hunter

$('#StartingPrice').lengthreturns an integer so it will never equal "".

$('#StartingPrice').length返回一个整数,所以它永远不会等于""

Try using the val()method:

尝试使用以下val()方法:

if($('#StartingPrice').val() == "")
{
    alert("ERROR!");
}


.length

。长度

The number of elements in the jQuery object.

jQuery 对象中的元素数。

.val()

.val()

Get the current value of the first element in the set of matched elements.

获取匹配元素集中第一个元素的当前值。

.value

。价值

No Such jQuery Method Exists

不存在这样的 jQuery 方法

回答by Naftali aka Neal

try this:

尝试这个:

if ($('#StartingPrice')[0].value.length == 0){
    alert("ERROR!");
}

回答by Brandon McKinney

Just as an alternative to the already provided solutions... you could also use a Regex to test that it actually contains something other than whitespace.

作为已经提供的解决方案的替代方案......您还可以使用正则表达式来测试它是否实际包含除空格以外的其他内容。

!!$('#StartingPrice').val().match(/\S/)

This will test for the existing of a non-whitespace character and using the Not-Not will convert it to a Boolean value for you. True if it contains non-whitespace. False if blank or only whitespace.

这将测试是否存在非空白字符,并使用 Not-Not 将其转换为布尔值。如果它包含非空格,则为真。如果空白或只有空格,则为 False。

回答by alexl

if ($('#StartingPrice').val() === ""){
    alert("ERROR!");
}

回答by d4nt

I think you want this:

我想你想要这个:

if ($('#StartingPrice').val() == false) {
    alert("Error!");
}

Use the .val() method to get the value and then pass that into the if. If the string is empty or white space it will evaluate to false.

使用 .val() 方法获取值,然后将其传递给 if。如果字符串为空或空白,它将评估为假。

回答by Raynos

if ($('#StartingPrice').val() == ""){
    alert("ERROR!");
}

If the value of your text input is any empty string then it's empty.

如果您的文本输入的值是任何空字符串,那么它就是空的。

回答by LooPer

Try:

尝试:

if(myStr){
   // Your code here
}