00 Votes

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

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

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

ReplyPositiveNegativeDateVotes
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.
2012-01-26 at 21:43

ReplyPositive Negative
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...
2012-01-28 at 17:14

ReplyPositive Negative
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.
2012-01-28 at 17:09

ReplyPositive Negative
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.
2012-01-31 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 article on askingbox.com. That’s how it’s done.