0 0 Votes

JavaScript: What is the best way to test for an empty string?

Question by Chematik | 26/01/2012 at 17:24

Question above. I want to know the best way to test whether a string is empty in JavaScript.

ReplyPositiveNegativeDateVotes

Progger99

Show Profile | Message
Avatar
00 Votes

If you only want to test, if a variable has any value, you can do it like this:

if (str) {
   alert('OK');
}

If you want to test, whether it is also a variable of the type String, you can proceed as follows:

if (str === '') {
   alert('OK');
}

The comparison operator with three equal signs tests on the one hand on the same content and on the other hand on the same type (in this case string); compared with ==, which only checks for the same content.
26/01/2012 at 21:43

ReplyPositive Negative

SimplyMe

Show Profile | Message
Avatar
00 Votes

You can also look at the length of the string, like this:

if (str.length == 0) {
   alert('String is empty.');
}

Or even more elegant:

if (!str.length) {
   alert('String is empty.');
}

There are certainly many ways...
28/01/2012 at 17:14

ReplyPositive Negative

NetGuy

Show Profile | Message
Avatar
00 Votes

I think the best solution is the following, so we can also see if our string is null:

if (!!str) {
   alert('Empty String!');
}

Only that works for me for a string that is undefined, null or empty.
28/01/2012 at 17:09

ReplyPositive Negative

Axuter

Show Profile | Message
Avatar
00 Votes

If we want to treat even strings that contain only white space, such as spaces or line breaks, as empty, we can do it like this:

if ((/^\s*$/).test(str)) {
   alert('emtpy string or only whitespace');
}

Of course, this is obviously something heavier in performance, than the other suggested solutions.
31/01/2012 at 21:37

ReplyPositive Negative
Reply

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own articles on askingbox.com. How to do.