如何检查变量是否为null或空字符串或JavaScript中的所有空格? [英] How to check if a variable is null or empty string or all whitespace in JavaScript?

查看:127
本文介绍了如何检查变量是否为null或空字符串或JavaScript中的所有空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检查一个变量是否为空或者是否为空(或空白。

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) {

}​

我需要的是像C#方法 String.IsNullOrWhiteSpace(value)

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

推荐答案

更接近模仿 IsNullOrWhiteSpace 的非jQuery解决方案,但要仅检测null,空或全空格:

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

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

...然后:

var addr = '  ';

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

*编辑*
请注意,op明确指出我需要检查var是否为null或者是否有任何空格或为此只是空白。所以,虽然是的,空格包含的不仅仅是null,空格还是空白,我的答案是为了回答op的具体问题。这很重要,因为op可能不想捕获像标签这样的东西,例如。

* EDIT * Please note that op specifically states "I need to check to see if a var is null or has any empty spaces or for that matter just 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.

这篇关于如何检查变量是否为null或空字符串或JavaScript中的所有空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆