Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to test for an empty string with jquery-out-of-the-box?

People also ask

How check string is empty or null in jQuery?

You can use exclamation mark ! to check if it is null. The above code means that if the $('#person_data[document_type]') has no value (if the value is null).

How do you test if a string string is empty?

Java String isEmpty() Method The isEmpty() method checks whether a string is empty or not. This method returns true if the string is empty (length() is 0), and false if not.


if (!a) {
  // is emtpy
}

To ignore white space for strings:

if (!a.trim()) {
    // is empty or whitespace
}

If you need legacy support (IE8-) for trim(), use $.trim or a polyfill.


The link you gave seems to be attempting something different to the test you are trying to avoid repeating.

if (a == null || a=='')

tests if the string is an empty string or null. The article you linked to tests if the string consists entirely of whitespace (or is empty).

The test you described can be replaced by:

if (!a)

Because in javascript, an empty string, and null, both evaluate to false in a boolean context.


Based on David's answer I personally like to check the given object first if it is a string at all. Otherwise calling .trim() on a not existing object would throw an exception:

function isEmpty(value) {
  return typeof value == 'string' && !value.trim() || typeof value == 'undefined' || value === null;
}

Usage:

isEmpty(undefined); // true
isEmpty(null); // true
isEmpty(''); // true
isEmpty('foo'); // false
isEmpty(1); // false
isEmpty(0); // false

To checks for all 'empties' like null, undefined, '', ' ', {}, [].

var isEmpty = function(data) {
    if(typeof(data) === 'object') {
        if(JSON.stringify(data) === '{}' || JSON.stringify(data) === '[]') {
            return true;
        } else if(!data) {
            return true;
        }
        return false;
    } else if(typeof(data) === 'string') {
        if(!data.trim()){
            return true;
        }
        return false;
    } else if(typeof(data) === 'undefined') {
        return true;
    } else {
        return false;
    }
}

Use cases and results.

console.log(isEmpty()); // true
console.log(isEmpty(null)); // true
console.log(isEmpty('')); // true
console.log(isEmpty('  ')); // true
console.log(isEmpty(undefined)); // true
console.log(isEmpty({})); // true
console.log(isEmpty([])); // true
console.log(isEmpty(0)); // false
console.log(isEmpty('Hey')); // false

Check if data is a empty string (and ignore any white space) with jQuery:

function isBlank( data ) {
    return ( $.trim(data).length == 0 );
}

if(!my_string){ 
// stuff 
}

and

if(my_string !== "")

if you want to accept null but reject empty

EDIT: woops, forgot your condition is if it IS empty