tags:

views:

124

answers:

6

Possible Duplicate:
What is the best way to check for an empty string in JavaScript?

I know this is really basic, but I am new to javascript and can't find an answer anywhere.

How can I check if a string is empty?

A: 
if (value == "") {
  // it is empty
}
Ray
If value is really a string, then this is correct, but it will also return true, if value = false or 0 or null. use === instead.
Residuum
@Residuum: The question reads “How to check if a string is empty?”
Gumbo
@Gumbo: An answer that works under all circumstances is in my opinion better than an answer that provides the bare minimum, so I agree with Residuum. Things like that are especially important to point out for a beginner.
OregonGhost
@Gumbo: As the question suggests, the questioner is not experienced in Javascript. And as Javascript is not a strongly typed language, it is a common source of error to not explicitly check for type as well. Been there, done that.
Residuum
+2  A: 

This should work:

if (variable === "") {

}
Tom Castle
If variable is really a string, then this is correct, but it will also return true, if variable = false or 0 or null. use === instead.
Residuum
You're quite right, it would be safer to use ===. Edited.
Tom Castle
A: 

if (mystring == '') alert('string is empty');

kekekela
+4  A: 

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.

nxt
+1  A: 

I check length.

if (str.length == 0) {
}
Dustin Laine
A: 

But for a better check:

if(str == "" || str == null)
{
    //enter code here
}
Christopher Richa
a null variable will have a length of 0, so why not use the length rather than two comparisons.
Dustin Laine
Actually I was going to edit this before it got closed: if(!str || str == "") { //enter code here }There are many ways to do this, but a String is not necessarily null if it has "" in it. Empty is **not** null.
Christopher Richa