Organizational Research By

Surprising Reserch Topic

How to check for an empty string in JavaScript?


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

asked Jun 30, 2015 in JAVASCRIPT by rajesh
0 votes
47 views



Related Hot Questions

2 Answers

0 votes

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

answered Jun 30, 2015 by rajesh
0 votes

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());
};
answered Jun 30, 2015 by rajesh

...