Advertisement
Advertisement


How can I check for an empty/undefined/null string in JavaScript?


Question

I saw this question, but I didn't see a JavaScript specific example. Is there a simple string.Empty available in JavaScript, or is it just a case of checking for ""?

2020/03/08
1
2952
3/8/2020 11:38:15 PM

Accepted Answer

If you just want to check whether there's any value, you can do

if (strValue) {
    //do something
}

If you need to check specifically for an empty string over null, I would think checking against "" is your best bet, using the === operator (so that you know that it is, in fact, a string you're comparing against).

if (strValue === "") {
    //...
}
2018/06/02
3702
6/2/2018 12:29:22 AM

For checking if a string is empty, null or undefined I use:

function isEmpty(str) {
    return (!str || 0 === str.length);
}

For checking if a string is blank, null or undefined I use:

function isBlank(str) {
    return (!str || /^\s*$/.test(str));
}

For checking if a string is blank or contains only white-space:

String.prototype.isEmpty = function() {
    return (this.length === 0 || !this.trim());
};
2014/05/13

All the previous answers are good, but this will be even better. Use the !!(not not) operator.

if(!!str){
    // Some code here
}

Or use type casting:

if(Boolean(str)){
    // Code here
}

Both do the same function. Typecast the variable to Boolean, where str is a variable.
It returns false for null,undefined,0,000,"",false.
It returns true for string "0" and whitespace " ".

2020/03/08

The closest thing you can get to str.Empty (with the precondition that str is a String) is:

if (!str.length) { ...
2018/08/31

If you need to make sure that the string is not just a bunch of empty spaces (I'm assuming this is for form validation) you need to do a replace on the spaces.

if(str.replace(/\s/g,"") == ""){
}
2008/09/30

I use:

function empty(e) {
  switch (e) {
    case "":
    case 0:
    case "0":
    case null:
    case false:
    case typeof(e) == "undefined":
      return true;
    default:
      return false;
  }
}

empty(null) // true
empty(0) // true
empty(7) // false
empty("") // true
empty((function() {
    return ""
})) // false
2020/03/08

Source: https://stackoverflow.com/questions/154059
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]