- How to check for an empty string in JavaScript
- If we need to check whether there’s any value in string,
- If we need to check specifically for an empty string over null, we would think checking against “” is our best, using the === operator (In fact, a string we are comparing against).
- To ignore white space for strings:
- If we need legacy support (IE8-) for trim(), use $.trim or a polyfill.
- check if the variable has a truthy value or not. That means
will evaluate to true if value is not:
- null
- undefined
- NaN
- empty string (“”)
- 0
- false
The above list represents all possible false values in ECMA-/Javascript. Find it in the specification at the ToBoolean section.
Furthermore, if we do not know whether a variable exists (that means, if it was declared) then we should check with the typeof operator. For instance
- Make sure that a variable is declared at least, we should directly check if it has a truthy value
- If a string is blank, null or undefined then we can use the following:
- If a string is blank or contains only white-space:
- Using !!(not not) operator:
or
Using type casting:
[ad type=”banner”]- Both do the same function, type cast the variable to boolean, where str is a variable.
- Returns false for null,undefined,0,000,””,false.
- Returns true for string “0” and whitespace ” “.
- Make sure that the string is not just a bunch of empty spaces (we are assuming this is for form validation) we need to replace on the spaces.
- We can use the following Solution:
- Several methods:
- Here we can use the regexps:
- Checks for strings that are either empty or filled with whitespace.
- For example, if we have a null character string:
- To test its nullness, we can do the following:
It works on a null string, and on an empty string and it is accessible for all strings. In addition, it could be expanded to contain other JavaScript empty or whitespace characters (i.e. nonbreaking space, byte order mark, line/paragraph separator, etc.).
- Starting with:
- Looking at the last condition, if value == “”, it’s length MUST be 0. Therefore drop it:
- In JS, an empty string is false. Therefore, drop value == “”:
- And !undefined is true, so that check isn’t needed. So we have:
- And we don’t need parentheses: