252

What is the best way to test for an empty string with jquery-out-of-the-box, i.e. without plugins? I tried this.

But it did't work at least out-of-the-box. It would be nice to use something that's builtin.

I wouldn't like to repeat

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

everywhere if some if (isempty(a)) would be available.

itzmebibin
  • 9,199
  • 8
  • 48
  • 62
Martin
  • 2,913
  • 4
  • 21
  • 15
  • 1
    possible duplicate of [What is the best way to check for an empty string in JavaScript?](http://stackoverflow.com/questions/154059/what-is-the-best-way-to-check-for-an-empty-string-in-javascript) – Adriano Carneiro Oct 28 '11 at 15:34
  • Possible duplicate of [How do you check for an empty string in JavaScript?](https://stackoverflow.com/questions/154059/how-do-you-check-for-an-empty-string-in-javascript) – T.Todua Dec 04 '18 at 09:33

9 Answers9

597
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.

David Hellsing
  • 106,495
  • 44
  • 176
  • 212
  • 1
    but does this check for ""? Doesn't that just check to see if it's null only and you need to also check for empty as empty is not the same as null? – PositiveGuy Nov 07 '11 at 07:16
  • 10
    @CoffeeAddict empty string is falsy in javascript, so yes, the expression evaluates to true if ``a`` is "" or any other falsy value (null, false, undefined, 0, NaN). – David Hellsing Nov 08 '11 at 06:17
  • what about spaces? is that an empty string? – Rafael Herscovici Jul 16 '13 at 16:25
  • 21
    If you need to also match strings with only whitespace, it's a good idea to use `if (!$.trim(a))` – Ilari Kajaste Jul 24 '13 at 19:11
  • 3
    In my experience the vast majority of times you want to run this test you also want it to include testing for whitespace. Since that is the usual-case, OP should include in his answer the comment from @IlariKajaste – Bane Aug 19 '13 at 17:25
  • 18
    The accepted answer will fail when you input a 0, however it will work for 1, 2, 3, 4 etc. – Steven Jun 19 '14 at 20:18
  • how is `if (!a)` superior than `if (a !== "")`? – Incerteza Jul 02 '14 at 07:19
  • how could it be designed to accept any type if the question says "string"? – Incerteza Jul 02 '14 at 10:32
  • @AlexanderSupertramp Then no, it’s not "superior", just simpler and less verbose. Both methods will do the job. – David Hellsing Jul 05 '14 at 17:08
  • 5
    Isn't `if (!a.trim())` a bit dangerous? What if `a` is undefined or null? – Timo Ernst Mar 20 '15 at 10:42
  • @Timo "dangerous" is a vague concept here. The question was about testing for an empty *string*, so raising an exception for `undefined` or `null` is not dangerous at all, it’s actually preferred. – David Hellsing Nov 11 '15 at 11:38
  • @David Sure, but I see no problem in adding a few more chars for improved practicality, see http://stackoverflow.com/questions/1812245/what-is-the-best-way-to-test-for-an-empty-string-with-jquery-out-of-the-box/33672308#33672308 – Timo Ernst Nov 12 '15 at 13:18
  • @timo If you are worried about types, I would do a simple type check (since JavaScript is loosely typed): `if (typeof a != 'string') throw new TypeError(a+' is not a string')`. This would prevent bugs like `1+'1'` later on in your chain. – David Hellsing Nov 27 '15 at 08:33
  • @Stevus `0` is not a *String*, which is what the OP asked. If you do this check on other types, you should be aware of JavaScript’s type coersion. – David Hellsing Mar 08 '17 at 13:01
  • @David - `0` is not a string, yes, however there is no type checking in the if statement, so the `if(!a) {}` will evaluate to true. Now if you want to be sure it is a string, use something like `typeof a === 'string' && !a` or something. – Steven Mar 15 '17 at 04:10
  • @Stevus Validating functional arguments and type checking is not the job of the function itself IMO, but that is a design decision and kind of irrelevant to the original question. But your point is valid since some people might not be aware of javascripts type coersion strategy... – David Hellsing Apr 05 '17 at 09:07
30

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.

SpoonMeiser
  • 19,918
  • 8
  • 50
  • 68
  • `if(!a)` wont it fail for a string consisting of say 4 spaces ? ` ` – KNU Nov 17 '15 at 06:45
  • @KNU Yes, but the question asks about an empty string, and a string comprising of spaces is not an empty string. See what I wrote about the difference between what was asked and what the linked code does – SpoonMeiser Nov 17 '15 at 07:02
  • This answer is wrong. It treats '0' like an empty string, which it isn't. – John Henckel Oct 21 '16 at 20:09
  • @JohnHenckel: It'll treat `0` like an empty string, but not `"0"`. I assume that's what you meant? It's conceivable that this is being used in a situation where you know that `a` is either a string, or null, but yes. Something to be aware of. – SpoonMeiser Oct 25 '16 at 12:33
28

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
Community
  • 1
  • 1
Timo Ernst
  • 15,243
  • 23
  • 104
  • 165
6

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

function isBlank( data ) {
    return ( $.trim(data).length == 0 );
}
aristotll
  • 8,694
  • 6
  • 33
  • 53
Sjoerd Linders
  • 447
  • 5
  • 8
5
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

Greg
  • 7,782
  • 7
  • 43
  • 69
2

Try executing this in your browser console or in a node.js repl.

var string = ' ';
string ? true : false;
//-> true

string = '';
string ? true : false;
//-> false

Therefore, a simple branching construct will suffice for the test.

if(string) {
    // string is not empty
}
Harry Love
  • 1,920
  • 1
  • 25
  • 25
2

Since you can also input numbers as well as fixed type strings, the answer should actually be:

function isBlank(value) {
  return $.trim(value);
}
Steven
  • 691
  • 3
  • 10
  • 26
-2

Try this

if(!a || a.length === 0)
Atif Aziz
  • 71
  • 7
-4
if((a.trim()=="")||(a=="")||(a==null))
{
    //empty condition
}
else
{
    //working condition
}
Shakti Phartiyal
  • 6,156
  • 3
  • 25
  • 46
  • If a is ``null`` then ``a.trim()`` would fail. This is a bad order to check things. And if you change the order, your answer does not provide anything, that has not been suggested before. – Mike Scotty May 16 '17 at 09:29