What is the best way to test for an empty string with jquery

What is the best way to test for an empty string with jquery-out-of-the-box, ie 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.


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
链接地址: http://www.djcxy.com/p/27526.html

上一篇: 属性与属性

下一篇: 用jquery测试空字符串的最佳方法是什么?