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 f
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());
}
var a;
existtrim out the false spaces
in the value, then test for emptiness
if ((a)&&(a.trim()!=''))
{
// if variable a is not empty do this
}
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
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
.
Also, in case you consider a whitespace filled string as "empty".
You can test it with this regular expression:
!/\S/.test(string); // Returns true if blank.
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
.