如何在 JavaScript 中检查变量是否为空或空字符串或所有空格?

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

How to check if a variable is null or empty string or all whitespace in JavaScript?

javascriptjquery

提问by Nate Pet

I need to check to see if a variable is null or has all empty spaces or is just blank ("").

我需要检查一个变量是否为空或全部为空格或只是空白(“”)。

I have the following, but it is not working:

我有以下内容,但它不起作用:

var addr;
addr = "  ";

if (!addr) {
    // pull error 
}

If I do the following, it works:

如果我执行以下操作,它会起作用:

if (addr) {

}?

What I need is something like the C# method String.IsNullOrWhiteSpace(value).

我需要的是类似于 C# 方法的东西String.IsNullOrWhiteSpace(value)

回答by Madbreaks

A non-jQuery solution that more closely mimics IsNullOrWhiteSpace, but to detect null, empty or all-spaces only:

一种非 jQuery 解决方案,它更接近地模拟IsNullOrWhiteSpace,但仅检测空、空或全空格:

function isEmptyOrSpaces(str){
    return str === null || str.match(/^ *$/) !== null;
}

...then:

...然后:

var addr = '  ';

if(isEmptyOrSpaces(addr)){
    // error 
}

* EDIT *Please note that op specifically states:

* 编辑 *请注意,op 特别指出:

I need to check to see if a var is null or has any empty spaces or for that matter just blank.

我需要检查 var是否为 null 或是否有任何空格,或者就此而言只是 blank

So while yes, "white space" encompasses more than null, spaces or blank my answer is intended to answer op's specific question. This is important because op may NOT want to catch things like tabs, for example.

因此,虽然是的,“空白”包含的不仅仅是空、空格或空白,但我的答案旨在回答 op 的具体问题。这很重要,因为 op 可能不想捕捉诸如标签之类的东西。

回答by ThiefMaster

You can use if(addr && (addr = $.trim(addr)))

您可以使用 if(addr && (addr = $.trim(addr)))

This has the advantage of actually removing any outer whitespace from addrinstead of just ignoring it when performing the check.

这具有实际删除任何外部空白的优点,addr而不是在执行检查时忽略它。

Reference: http://api.jquery.com/jQuery.trim/

参考:http: //api.jquery.com/jQuery.trim/

回答by Ricardo Tomasi

if (addr == null || addr.trim() === ''){
  //...
}

A nullcomparison will also catch undefined. If you want falseto pass too, use !addr. For backwards browser compatibility swap addr.trim()for $.trim(addr).

一个null比较也将赶上undefined。如果您也想false通过,请使用!addr. 为了向后浏览器兼容性掉addr.trim()$.trim(addr)

回答by Shehzad

You can create your own method Equivalent to

您可以创建自己的方法相当于

String.IsNullOrWhiteSpace(value)

String.IsNullOrWhiteSpace(value)

function IsNullOrWhiteSpace( value) {

    if (value== null) return true;

    return value.replace(/\s/g, '').length == 0;
}

回答by Ali

isEmptyOrSpaces(str){
    return !str || str.trim() === '';
}

回答by sandre89

Old question, but I think it deservers a simpler answer.

老问题,但我认为它值得一个更简单的答案。

You can simply do:

你可以简单地做:

var addr = "  ";

if (addr & addr.trim()) {

    console.log("I'm not null, nor undefined, nor empty string, nor string composed of whitespace only.");

}

回答by Aaron Hoffman

Simplified version of the above: (from here: https://stackoverflow.com/a/32800728/47226)

上面的简化版本:(来自这里:https: //stackoverflow.com/a/32800728/47226

function isNullOrWhitespace( input ) {
  return !input || !input.trim();
}

回答by Joao Leme

When checking for white space the c# method uses the Unicode standard. White space includes spaces, tabs, carriage returns and many other non-printing character codes. So you are better of using:

检查空格时,c# 方法使用 Unicode 标准。空白包括空格、制表符、回车和许多其他非打印字符代码。所以你最好使用:

function isNullOrWhiteSpace(str){
    return str == null || str.replace(/\s/g, '').length < 1;
}

回答by hamedalavi

You can try this:

你可以试试这个:

do {
   var op = prompt("please input operatot \n you most select one of * - / *  ")
} while (typeof op == "object" || op == ""); 
// execute block of code when click on cancle or ok whthout input

回答by Rod lauro Romarate

Try this out

试试这个

/**
  * Checks the string if undefined, null, not typeof string, empty or space(s)
  * @param {any} str string to be evaluated
  * @returns {boolean} the evaluated result
*/
function isStringNullOrWhiteSpace(str) {
    return str === undefined || str === null
                             || typeof str !== 'string'
                             || str.match(/^ *$/) !== null;
}

You can use it like this

你可以像这样使用它

isStringNullOrWhiteSpace('Your String');