Question

I saw this thread, 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 ""?

Was it helpful?

Solution

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 === "") {
    //...
}

OTHER TIPS

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());
};

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

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,"") == ""){
}

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

if (!str.length) { ...

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 ""
  })) // false

Try:

if (str && str.trim().length) {  
    //...
}

Function:

function is_empty(x)
{
   return ( 
        (typeof x == 'undefined')
                    ||
        (x == null) 
                    ||
        (x == false)  //same as: !x
                    ||
        (x.length == 0)
                    ||
        (x == "")
                    ||
        (x.replace(/\s/g,"") == "")
                    ||
        (!/[^\s]/.test(x))
                    ||
        (/^\s*$/.test(x))
  );
}

p.s. In Javascript, don't use Line-Break after return;

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

You can use lodash : _.isEmpty(value).

It covers a lot of cases like {}, '', null, undefined etc.

But it always returns true for Number type of Javascript Primitive Data Types like _.isEmpty(10) or _.isEmpty(Number.MAX_VALUE) both returns true.

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 could some how end up containing an integer 0 value, then that would indeed be one of those intention-clarifying situations.

you could also go with regexps:

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

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

A lot of answers, and a lot of different possibilities!

Without a doubt for quick and simple implementation the winner is: if (!str.length) {...}

However, as many other examples are available. The best functional method to go about this, I would suggest:

function empty(str)
{
    if (typeof str == 'undefined' || !str || str.length === 0 || str === "" || !/[^\s]/.test(str) || /^\s*$/.test(str) || str.replace(/\s/g,"") === "")
    {
        return true;
    }
    else
    {
        return false;
    }
}

A bit excessive, I know.

  1. check that var a; exist
  2. trim out the false spaces in the value, then test for emptiness

    if ((a)&&(a.trim()!=''))
    {
      // if variable a is not empty do this 
    }
    

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.

I usually use some thing like this,

if (!str.length) {
//do some thing
}

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

If one needs to detect not only empty but also blank strings, I'll add to Goral's answer:

function isEmpty(s){
    return !s.length;    
}

function isBlank(s){
    return isEmpty(s.trim());    
}

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.

I usually use something like:

if (str == "") {
     //Do Something
}
else {
     //Do Something Else
}

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);
}

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.

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; } }]
];

to check if is exactly an empty string:

if(val==="")...

to check if it is an empty string OR a a logical equivalent for no-value (null, undefined, 0, NaN, false, ...):

if(!val)...

Meanwhile we can have one function that checks for all 'empties' like null, undefined, '', ' ', {}, []. So I just wrote this.

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

There's no isEmpty() method, you have to check for the type and the length:

if (typeof test === 'string' && test.length === 0){
  ...

The type check is needed in order to avoid runtime errors when test is undefined or null.

Don't assume that the variable you check is a string. Don't assume that if this var has a length, then it's a string.

The thing is: think carefully about what your app must do and can accept. Build something robust.

If your method / function should only process a non empty string then test if the argument is a non empty string and don't do some 'trick'.

As an example of something that will explode if you follow some advices here not carefully.


var getLastChar = function (str) {
 if (str.length > 0)
   return str.charAt(str.length - 1)
}

getLastChar('hello')
=> "o"

getLastChar([0,1,2,3])
=> TypeError: Object [object Array] has no method 'charAt'

So, I'd stick with


if (myVar === '')
  ...

Try this

str.value.length == 0

You can easily add it to native String object in JavaScript and reuse it over and over...
Something simple like below code can do the job for you if you want to check '' empty strings:

String.prototype.isEmpty = String.prototype.isEmpty || function() {
  return !(!!this.length);
}

Otherwise if you'd like to check both '' empty string and ' ' with space, you can do that by just adding trim(), something like the code below:

String.prototype.isEmpty = String.prototype.isEmpty || function() {
   return !(!!this.trim().length);
}

and you can call it this way:

''.isEmpty(); //return true
'alireza'.isEmpty(); //return false
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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top