Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check for an empty/undefined/null string in JavaScript?

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

like image 380
casademora Avatar asked Sep 30 '08 17:09

casademora


People also ask

How do you check a value is empty null or undefined in JavaScript?

Check for null variable using strict equality operator (===) In this method, we will use the strict equality operator to check whether a variable is null, empty, or undefined. If we don't assign the value to the variable while declaring, the JavaScript compiler assigns it to the 'undefined' value.

How do you check if a string is empty or undefined in JavaScript?

Say, if a string is empty var name = "" then console. log(! name) returns true . this function will return true if val is empty, null, undefined, false, the number 0 or NaN.

Is empty string null in JavaScript?

The value null represents the absence of any object, while the empty string is an object of type String with zero characters. If you try to compare the two, they are not the same.

How do I check if a string is empty or null?

You can use the IsNullOrWhiteSpace method to test whether a string is null , its value is String. Empty, or it consists only of white-space characters.


2 Answers

If you just want to check whether there's a truthy 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 === "") {     //... } 
like image 97
bdukes Avatar answered Oct 08 '22 04:10

bdukes


For checking if a variable is falsey or if it has length attribute equal to zero (which for a string, means it is empty), I use:

function isEmpty(str) {     return (!str || str.length === 0 ); } 

(Note that strings aren't the only variables with a length attribute, arrays have them as well, for example.)

For checking if a variable is falsey or if the string only contains whitespace or is empty, I use:

function isBlank(str) {     return (!str || /^\s*$/.test(str)); } 

If you want, you can monkey-patch the String prototype like this:

String.prototype.isEmpty = function() {     // This doesn't work the same way as the isEmpty function used      // in the first example, it will return true for strings containing only whitespace     return (this.length === 0 || !this.trim()); }; console.log("example".isEmpty()); 

Note that monkey-patching built-in types is controversial, as it can break code that depends on the existing structure of built-in types, for whatever reason.

like image 43
Jano González Avatar answered Oct 08 '22 04:10

Jano González