Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: How to check if a string is empty? [duplicate]

People also ask

How do you check whether a string is empty or not in JavaScript?

To check if a string is empty, access its length property and check if it's equal to 0 , e.g. if (str. length === 0) {} . If the string's length is equal to 0 , then the string is empty, otherwise it isn't empty.

Is empty string null in JavaScript?

The value null represents the absence of any object, while the empty string is an object of type String with zero characters. If you try to compare the two, they are not the same.

Is empty string false or true?

Yes. All false , 0 , empty strings '' and "" , NaN , undefined , and null are always evaluated as false ; everything else is true .


I check length.

if (str.length == 0) {
}

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.

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


This should work:

if (variable === "") {

}

But for a better check:

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