Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

share|improve this question
just FYI, i think the most useful APIs for the String class are at Mozilla and javascript kit. [elated.com](elated.com/articles/working-with-strings ) has a tutorial on all of String's properties, methods,... Please note: the Mozilla link has been updated to developer.mozilla.org/en/JavaScript/Reference/Global_Objects/… – Gene T Oct 2 '08 at 15:16

22 Answers

up vote 688 down vote accepted

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

share|improve this answer
6  
Excellent answer, well written. – Raithlin Sep 30 '08 at 17:43
34  
(Would be even better if you mentioned that === also checks that the two are the same type) – Chris Noe Sep 30 '08 at 18:46
13  
Testing the length property may actually be faster than testing the string against "", because the interpreter won't have to create a String object from the string literal. – Vincent Robert Oct 1 '08 at 20:07
5  
@bdukes when you start to care about that kind of micro-optimizations, I don't think Chrome is the browser where you are having most of your performance problems... – Vincent Robert Sep 27 '10 at 16:18
3  
Point taken, I just don't have the motivation to figure out how to profile something like that in IE6... – bdukes Sep 27 '10 at 17:16
show 5 more comments

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));
}
share|improve this answer
12  
+1 For making functions that makes code more readable – Brimstedt Mar 15 '12 at 8:24
sencod example, a little better example would be: /[^\s]/.test(str) – Rok Kralj Apr 15 '12 at 12:21
   
@RokKralj - your 'better example' fails as it only tests that the string contains white spaces, not that it is entirely white spaces. Try testing against the string 'x x' – Chris Apr 16 '12 at 13:55
2  
(!str || !str.length) – ajax333221 Apr 18 '12 at 15:22
1  
@RokKralj I think you meant !/[^\s]/.test(str) or shorter !/\S/.test(str) – Bracketworks Mar 8 at 16:43
show 2 more comments

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,"") == ""){
}
share|improve this answer
34  
Now that's an expensive test – Chris Noe Sep 30 '08 at 23:26
5  
But does the job if what you actually want to test for is a string with non-space content. Is there a less-expensive way to test this? – flashparry Oct 22 '10 at 10:02
1  
How about the length property? – driAn Nov 11 '10 at 13:57
11  
Instead of removing all the spaces, why not just check if there's a non-space? Has 2 advantages that it can bail out early if there is a non-space character, and it doesn't have return a new string which you then check against. if(str.match(/\S/g)){} – Mark Jun 20 '11 at 4:29
19  
@Mark FYI, you wouldn't need the global modifier, since the match of the first occurrence of a non-space character would mean the string is not empty: str.match(/\S/) – neezer Jun 27 '11 at 15:04
show 6 more comments

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

if (!str.length) { ...
share|improve this answer
the best desicion infact!! – holms Jun 9 '10 at 15:07
2  
This is the best solution. An alternative would be (str === "") – finishingmove Apr 17 at 21:59

All the above are good but this will be even better. use !!(not not) operator.

if(!!str){
some code here;
}

or use type casting:

if(Boolean(str)){
    codes here;
}

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

share|improve this answer
4  
Why is this "even better"? – Mene Apr 3 '11 at 13:04
2  
Of all the suggested solutions on this page, this is the only one if(!!str) that works! Undefined, Null, Empty String are all handled without issue. – Rob Sep 22 '11 at 15:17
tried a few of the others and they wouldn't work for my situation with a null value. these work great. – smerny Feb 15 '12 at 19:36

I would not worry too much about the most efficient method. Use what is most clear to your intention. For me that's usually strVar == "".

EDIT: per comment from Constantin, if strVar some how ended up containing an integer 0 value, then strVar == "" returns true. So if that is a danger in your situation, you should code strVar === "", which ensures that the types are also the same.

share|improve this answer
3  
Bad idea. You'll get true if strVar is accidentally assigned 0. – Constantin Sep 30 '08 at 19:21

you could also go with regexps:

if((/^\s*$/).test(str)) { }

Checks for strings that are either empty or filled with whitespace.

share|improve this answer
it really worked for me – waqari Sep 21 '11 at 5:25
var s; // undefined
var s = ""; // ""
s.length // 0

There's nothing representing an empty string in JavaScript. Do a check against either length (if you know that the var will always be a string) or against ""

share|improve this answer

I use :

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

empty(null) // true
empty(0) // true
empty(7) // false
empty("") // true
empty((function() { return "" }) ) // true
share|improve this answer
10  
hells solution. – Evgeny Feb 25 '11 at 10:22
This solution is more language agnostic. The only JavaScript feature it relies on is typeof. So it is a good example of a solution you can use when you don't trust the implementations in different browsers and don't have time to grab a better solution. (IE, no internet access). It's something like a proof. Not the cleanest but you can be sure it will work without knowing too much about JavaScript. – Jeff Davis Apr 20 '12 at 13:11

I use a combination, fastest checks are first.

function isBlank(pString){
    if (!pString || pString.length == 0) {
        return true;
    }
    // checks for a non-white space character 
    // which I think [citation needed] is faster 
    // than removing all the whitespace and checking 
    // against an empty string
    return !/[^\s]+/.test(pString);
}
share|improve this answer
Just wondering if you could explain when the length check would be necessary? Wouldn't !pString catch anything that was null/empty string? This seems to work. var test=''; if (!test) alert('empty'); – Nicholi Oct 27 '11 at 21:49

I have not noticed an answer that takes into account the possibility of null characters in a string. For example, if we have a null character string:

var y = "\0"; // an empty string, but has a null character
(y === "") // false, testing against an empty string does not work
(y.length === 0) // false
(y) // true, this is also not expected
(y.match(/^[\s]*$/)) // false, again not wanted

To test its nullness one could do something like this:

String.prototype.isNull = function(){ 
  return Boolean(this.match(/^[\0]*$/)); 
}
...
"\0".isNull() // true

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

share|improve this answer
Interesting analysis. I don't think this would be relevant in 99.9% of cases. BUT I recently found that MySQL evaluates a column to "null" if (and only if) that column contains the null character ("\0"). Oracle on the other hand would not evaluate "\0" as being null, preferring to treat it as a string of length 1 (where that one character is the null character). This could cause confusion if not dealt with properly, because many web-developers do work with a back-end database, which might pass through different types of "null" values. It should be at the back of every developer's mind. – cartbeforehorse Oct 20 '12 at 12:20

I usually use something like:

if (str == "") {
     //Do Something
}
else {
     //Do Something Else
}
share|improve this answer

Ignoring whitespace strings, you could use this to check for null, empty and undefined :

var obj = {};
(!!obj.str) //returns false

obj.str = "";
(!!obj.str) //returns false

obj.str = null;
(!!obj.str) //returns false

Concise and it works for undefined properties, although it's not the most readable.

share|improve this answer

str.value.length == 0

share|improve this answer
function tell()
{
var pass = document.getElementById('pasword').value;
var plen = pass.length;

now you can check if your string is empty as like 
if(plen==0)
{
         alert('empty');
}
else
{
   alert('you entered something');
}
}


<input type='text' id='pasword' />

this is also a generic way to check if field is empty.

share|improve this answer

Also, in case you consider a whitespace filled string as "empty". You can test it with this Regex:

!/\S/.test(string); // Returns true if blank.
share|improve this answer

It's a good idea too to check that you are not trying to pass an undefined term.

function TestMe() {
  if((typeof str != 'undefined') && str) {
    alert(str);
  }
 };

TestMe();

var str = 'hello';

TestMe();

I usually run into the case where I want to do something when a string attribute for an object instance is not empty. Which is fine, except that attribute is not always present.

share|improve this answer

Try:

if (str && str.trim().length) {  
    //...
}
share|improve this answer

An alternative way, but I believe bdukes's answer is best.

   var myString = 'hello'; 
    if(myString.charAt(0)){
    alert('no empty');
    }
    alert('empty');
share|improve this answer

All these answers are nice.

But I cannot be sure that variable is a string, doesn't contains only spaces (this is important for me), and can contain '0' (string).

My version:

function empty(str){
    return !str || !/[^\s]+/.test(str);
}

empty(null); // true
empty(0); // true
empty(7); // false
empty(""); // true
empty("0"); // false
empty("  "); // true

Sample on jsfiddle.

share|improve this answer

I did some research what happens if you pass a non-string and non-empty/null value to a tester function. As many knows, (0 == "") is true in javascript, but since 0 is a value and not empty or null, you may want to test for it.

The following two functions return true only for undefined, null, empty/whitespace values and false for everything else, such as numbers, boolean, objects, expressions etc.

function IsNullOrEmpty(value)
{
    return (value == null || value === "");
}
function IsNullOrWhiteSpace(value)
{
    return (value == null || !/\S/.test(value));
}

More complicated examples exists, but these are simple and give consistent results. There is no need to test for undefined, since it's included in (value == null) check. You may also mimic C# behaviour by adding them to String like this:

String.IsNullOrEmpty = function (value) { ... }

You do not want to put it in Strings prototype, because if the instance of the String-class is null, it will error:

String.prototype.IsNullOrEmpty = function (value) { ... }
var myvar = null;
if (1 == 2) { myvar = "OK"; } // could be set
myvar.IsNullOrEmpty(); // throws error

I tested with the following value array. You can loop it through to test your functions if in doubt.

// Helper items
var MyClass = function (b) { this.a = "Hello World!"; this.b = b; };
MyClass.prototype.hello = function () { if (this.b == null) { alert(this.a); } else { alert(this.b); } };
var z;
var arr = [
// 0: Explanation for printing, 1: actual value
    ['undefined', undefined],
    ['(var) z', z],
    ['null', null],
    ['empty', ''],
    ['space', ' '],
    ['tab', '\t'],
    ['newline', '\n'],
    ['carriage return', '\r'],
    ['"\\r\\n"', '\r\n'],
    ['"\\n\\r"', '\n\r'],
    ['" \\t \\n "', ' \t \n '],
    ['" txt \\t test \\n"', ' txt \t test \n'],
    ['"txt"', "txt"],
    ['"undefined"', 'undefined'],
    ['"null"', 'null'],
    ['"0"', '0'],
    ['"1"', '1'],
    ['"1.5"', '1.5'],
    ['"1,5"', '1,5'], // valid number in some locales, not in js
    ['comma', ','],
    ['dot', '.'],
    ['".5"', '.5'],
    ['0', 0],
    ['0.0', 0.0],
    ['1', 1],
    ['1.5', 1.5],
    ['NaN', NaN],
    ['/\S/', /\S/],
    ['true', true],
    ['false', false],
    ['function, returns true', function () { return true; } ],
    ['function, returns false', function () { return false; } ],
    ['function, returns null', function () { return null; } ],
    ['function, returns string', function () { return "test"; } ],
    ['function, returns undefined', function () { } ],
    ['MyClass', MyClass],
    ['new MyClass', new MyClass()],
    ['empty object', {}],
    ['non-empty object', { a: "a", match: "bogus", test: "bogus"}],
    ['object with toString: string', { a: "a", match: "bogus", test: "bogus", toString: function () { return "test"; } }],
    ['object with toString: null', { a: "a", match: "bogus", test: "bogus", toString: function () { return null; } }]
];
share|improve this answer

I prefer to use not blank test instead of blank

function isNotBlank(str) {
   return (str && /^\s*$/.test(str));
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.