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
Reply
Related Topics
PHP: Check Strings with Ctype-Functions for Character Classes
Article | 0 Comments
PHP: Remove all empty elements from string array
Tip | 0 Comments
What are the categories at the Oscars?
Info | 0 Comments
HTML5 Validator: How to fix "Warning trimming empty <p> or <div>"
Question | 1 Answer
Java: Case Insensitive Equals - String Comparison
Info | 0 Comments
JavaScript: Remove last character from string
Tip | 5 Comments
JavaScript: Catch Submit of Form
Tutorial | 0 Comments
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.
If you only want to test, if a variable has any value, you can do it like this:
If you want to test, whether it is also a variable of the type String, you can proceed as follows:
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
You can also look at the length of the string, like this:
Or even more elegant:
There are certainly many ways...
2012-01-28 at 17:14
I think the best solution is the following, so we can also see if our string is null:
Only that works for me for a string that is undefined, null or empty.
2012-01-28 at 17:09
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:
Of course, this is obviously something heavier in performance, than the other suggested solutions.
2012-01-31 at 21:37