How to check empty/undefined/null string in JavaSc

2018-12-31 03:34发布

I saw this thread, but I didn't see a JavaScript specific example. Is there a simple string.Empty available in JavaScript, or is it just a case of checking for ""?

30条回答
孤独总比滥情好
2楼-- · 2018-12-31 04:20

All the above are good but this will be even better. use !!(not not) operator.

if(!!str){
some code here;
}

or use type casting:

if(Boolean(str)){
    codes here;
}

Both do the same function, type cast the variable to boolean, where str is a variable.
Returns false for null,undefined,0,000,"",false.
Returns true for string "0" and whitespace " ".

查看更多
梦醉为红颜
3楼-- · 2018-12-31 04:20

You can use lodash : _.isEmpty(value).

It covers a lot of cases like {}, '', null, undefined etc.

But it always returns true for Number type of Javascript Primitive Data Types like _.isEmpty(10) or _.isEmpty(Number.MAX_VALUE) both returns true.

查看更多
墨雨无痕
4楼-- · 2018-12-31 04:20
  1. check that var a; exist
  2. trim out the false spaces in the value, then test for emptiness

    if ((a)&&(a.trim()!=''))
    {
      // if variable a is not empty do this 
    }
    
查看更多
妖精总统
5楼-- · 2018-12-31 04:20
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' />

this is also a generic way to check if field is empty.

查看更多
素衣白纱
6楼-- · 2018-12-31 04:23

If you just want to check whether there's any value, you can do

if (strValue) {
    //do something
}

If you need to check specifically for an empty string over null, I would think checking against "" is your best bet, using the === operator (so that you know that it is, in fact, a string you're comparing against).

if (strValue === "") {
    //...
}
查看更多
还给你的自由
7楼-- · 2018-12-31 04:23

Try:

if (str && str.trim().length) {  
    //...
}
查看更多
登录 后发表回答