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 ""
?
This question is related to
javascript
null
is-empty
I didn't see a good answer here (at least not an answer that fits for me)
So I decided to answer myself:
value === undefined || value === null || value === "";
You need to start checking if it's undefined. Otherwise your method can explode, and then you can check if it equals null or is equal to an empty string.
You cannot have !! or only if(value)
since if you check 0
it's going to give you a false answer (0 is false).
With that said, wrap it up in a method like:
public static isEmpty(value: any): boolean {
return value === undefined || value === null || value === "";
}
PS.: You don't need to check typeof, since it would explode and throw even before it enters the method
I did some research on what happens if you pass a non-string and non-empty/null value to a tester function. As many know, (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 JavaScript
['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; } }]
];
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
It is concise and it works for undefined properties, although it's not the most readable.
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());
};
I perform tests on macOS v10.13.6 (High Sierra) for 18 chosen solutions. Solutions works slightly different (for corner-case input data) which was presented in the snippet below.
Conclusions
!str
,==
,===
and length
are fast for all browsers (A,B,C,G,I,J)test
,replace
) and charAt
are slowest for all browsers (H,L,M,P)In the below snippet I compare results of chosen 18 methods by use different input parameters
""
"a"
" "
- empty string, string with letter and string with space[]
{}
f
- array, object and function0
1
NaN
Infinity
- numberstrue
false
- Booleannull
undefined
Not all tested methods support all input cases.
function A(str) {_x000D_
let r=1;_x000D_
if (!str)_x000D_
r=0;_x000D_
return r;_x000D_
}_x000D_
_x000D_
function B(str) {_x000D_
let r=1;_x000D_
if (str == "")_x000D_
r=0;_x000D_
return r;_x000D_
}_x000D_
_x000D_
function C(str) {_x000D_
let r=1;_x000D_
if (str === "")_x000D_
r=0;_x000D_
return r;_x000D_
}_x000D_
_x000D_
function D(str) {_x000D_
let r=1;_x000D_
if(!str || 0 === str.length)_x000D_
r=0;_x000D_
return r;_x000D_
}_x000D_
_x000D_
function E(str) {_x000D_
let r=1;_x000D_
if(!str || /^\s*$/.test(str))_x000D_
r=0;_x000D_
return r;_x000D_
}_x000D_
_x000D_
function F(str) {_x000D_
let r=1;_x000D_
if(!Boolean(str))_x000D_
r=0;_x000D_
return r;_x000D_
}_x000D_
_x000D_
function G(str) {_x000D_
let r=1;_x000D_
if(! ((typeof str != 'undefined') && str) )_x000D_
r=0;_x000D_
return r;_x000D_
}_x000D_
_x000D_
function H(str) {_x000D_
let r=1;_x000D_
if(!/\S/.test(str))_x000D_
r=0;_x000D_
return r;_x000D_
}_x000D_
_x000D_
function I(str) {_x000D_
let r=1;_x000D_
if (!str.length)_x000D_
r=0;_x000D_
return r;_x000D_
}_x000D_
_x000D_
function J(str) {_x000D_
let r=1;_x000D_
if(str.length <= 0)_x000D_
r=0;_x000D_
return r;_x000D_
}_x000D_
_x000D_
function K(str) {_x000D_
let r=1;_x000D_
if(str.length === 0 || !str.trim())_x000D_
r=0;_x000D_
return r;_x000D_
}_x000D_
_x000D_
function L(str) {_x000D_
let r=1;_x000D_
if ( str.replace(/\s/g,"") == "")_x000D_
r=0;_x000D_
return r;_x000D_
}_x000D_
_x000D_
function M(str) {_x000D_
let r=1;_x000D_
if((/^\s*$/).test(str))_x000D_
r=0;_x000D_
return r;_x000D_
}_x000D_
_x000D_
_x000D_
function N(str) {_x000D_
let r=1;_x000D_
if(!str || !str.trim().length)_x000D_
r=0;_x000D_
return r;_x000D_
}_x000D_
_x000D_
function O(str) {_x000D_
let r=1;_x000D_
if(!str || !str.trim())_x000D_
r=0;_x000D_
return r;_x000D_
}_x000D_
_x000D_
function P(str) {_x000D_
let r=1;_x000D_
if(!str.charAt(0))_x000D_
r=0;_x000D_
return r;_x000D_
}_x000D_
_x000D_
function Q(str) {_x000D_
let r=1;_x000D_
if(!str || (str.trim()==''))_x000D_
r=0;_x000D_
return r;_x000D_
}_x000D_
_x000D_
function R(str) {_x000D_
let r=1;_x000D_
if (typeof str == 'undefined' ||_x000D_
!str ||_x000D_
str.length === 0 ||_x000D_
str === "" ||_x000D_
!/[^\s]/.test(str) ||_x000D_
/^\s*$/.test(str) ||_x000D_
str.replace(/\s/g,"") === "")_x000D_
_x000D_
r=0;_x000D_
return r;_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
// --- TEST ---_x000D_
_x000D_
console.log( ' "" "a" " " [] {} 0 1 NaN Infinity f true false null undefined ');_x000D_
let log1 = (s,f)=> console.log(`${s}: ${f("")} ${f("a")} ${f(" ")} ${f([])} ${f({})} ${f(0)} ${f(1)} ${f(NaN)} ${f(Infinity)} ${f(f)} ${f(true)} ${f(false)} ${f(null)} ${f(undefined)}`);_x000D_
let log2 = (s,f)=> console.log(`${s}: ${f("")} ${f("a")} ${f(" ")} ${f([])} ${f({})} ${f(0)} ${f(1)} ${f(NaN)} ${f(Infinity)} ${f(f)} ${f(true)} ${f(false)}`);_x000D_
let log3 = (s,f)=> console.log(`${s}: ${f("")} ${f("a")} ${f(" ")}`);_x000D_
_x000D_
log1('A', A);_x000D_
log1('B', B);_x000D_
log1('C', C);_x000D_
log1('D', D);_x000D_
log1('E', E);_x000D_
log1('F', F);_x000D_
log1('G', G);_x000D_
log1('H', H);_x000D_
_x000D_
log2('I', I);_x000D_
log2('J', J);_x000D_
_x000D_
log3('K', K);_x000D_
log3('L', L);_x000D_
log3('M', M);_x000D_
log3('N', N);_x000D_
log3('O', O);_x000D_
log3('P', P);_x000D_
log3('Q', Q);_x000D_
log3('R', R);
_x000D_
And then for all methods I perform speed test case str = ""
for browsers Chrome v78.0.0, Safari v13.0.4, and Firefox v71.0.0 - you can run tests on your machine here
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
}
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.).
Try:
if (str && str.trim().length) {
//...
}
Try this:
export const isEmpty = string => (!string || !string.length);
You should always check for the type too, since JavaScript is a duck typed language, so you may not know when and how the data changed in the middle of the process. So, here's the better solution:
let undefinedStr;
if (!undefinedStr) {
console.log("String is undefined");
}
let emptyStr = "";
if (!emptyStr) {
console.log("String is empty");
}
let nullStr = null;
if (!nullStr) {
console.log("String is null");
}
_x000D_
The following regular expression is another solution, that can be used for null, empty or undefined string.
(/(null|undefined|^$)/).test(null)
I added this solution, because it can be extended further to check empty or some value like as follow. The following regular expression is checking either string can be empty null undefined or it has integers only.
(/(null|undefined|^$|^\d+$)/).test()
The closest thing you can get to str.Empty
(with the precondition that str is a String) is:
if (!str.length) { ...
I usually use something like this,
if (!str.length) {
// Do something
}
An alternative way, but I believe bdukes's answer is best.
var myString = 'hello';
if(myString.charAt(0)){
alert('no empty');
}
alert('empty');
Check all the below scenarios:
null
undefined
0
"" (the empty string)
false
NaN
This function has worked well for me, assuring that it's both a string and not empty:
isNonBlankString = function(s) { return ((typeof s === 'string' || s instanceof String) && s !== ''); }
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,"") == ""){
}
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
The Underscore.js JavaScript library, http://underscorejs.org/, provides a very useful _.isEmpty()
function for checking for empty strings and other empty objects.
Reference: http://underscorejs.org/#isEmpty
isEmpty
_.isEmpty(object)
Returns true if an enumerable object contains no values (no enumerable own-properties). For strings and array-like objects _.isEmpty checks if the length property is 0.
_.isEmpty([1, 2, 3]);
=> false
_.isEmpty({});
=> true
Other very useful Underscore.js functions include:
_.isNull(object)
_.isUndefined(value)
_.has(object, key)
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
.
As of now there is no direct method like string.empty to check whether a string is empty or not. But in your code you can use a wrapper check for an empty string like:
// considering the variable in which your string is saved is named str.
if (str && str.length>0) {
// Your code here which you want to run if the string is not empty.
}
Using this you can also make sure that string is not undefined or null too. Remember, undefined, null and empty are three different things.
var x =" ";
var patt = /^\s*$/g;
isBlank = patt.test(x);
alert(isBlank); // Is it blank or not??
x = x.replace(/\s*/g, ""); // Another way of replacing blanks with ""
if (x===""){
alert("ya it is blank")
}
You could also go with regular expressions:
if((/^\s*$/).test(str)) { }
Checks for strings that are either empty or filled with whitespace.
Try this
str.value.length == 0
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.
Very generic "All-In-One" Function (not recommended though):
function is_empty(x)
{
return ( //don't put newline after return
(typeof x == 'undefined')
||
(x == null)
||
(x == false) //same as: !x
||
(x.length == 0)
||
(x == 0) // note this line, you might not need this.
||
(x == "")
||
(x.replace(/\s/g,"") == "")
||
(!/[^\s]/.test(x))
||
(/^\s*$/.test(x))
);
}
However, I don't recommend to use that, because your target variable should be of specific type (i.e. string, or numeric, or object?), so apply the checks that are relative to that variable.
in case of checking the empty string simply
if (str.length){
//do something
}
if you also want to include null & undefined with your check simply
if (Boolean(str)){
//this will be true when the str is not empty nor null nor undefined
}
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
All the previous answers are good, but this will be even better. Use dual NOT operators (!!
):
if (!!str) {
// Some code here
}
Or use type casting:
if (Boolean(str)) {
// Code here
}
Both do the same function. Typecast the variable to Boolean, where str
is a variable.
It returns false
for null
, undefined
, 0
, 000
, ""
, false
.
It returns true
for string "0"
and whitespace " "
.
You can check this using the typeof operator along with the length method.
const isEmptyString = (value) => typeof(value) == 'string' && value.length > 0
To check if it is empty:
var str = "Hello World!";
var n = str.length;
if(n === ''){alert("THE STRING str is EMPTY");}
To check if it isn't empty
var str = "Hello World!";
var n = str.length;
if(n != ''){alert("THE STRING str isn't EMPTY");}
I use:
function empty(e) {
switch (e) {
case "":
case 0:
case "0":
case null:
case false:
case typeof(e) == "undefined":
return true;
default:
return false;
}
}
empty(null) // true
empty(0) // true
empty(7) // false
empty("") // true
empty((function() {
return ""
})) // false
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;
}
_x000D_
A bit excessive, I know.
To check if it is exactly an empty string:
if(val==="")...
To check if it is an empty string OR a logical equivalent for no-value (null, undefined, 0, NaN, false, ...):
if(!val)...
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 == ""
.
As per the 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.
I prefer to use not blank test instead of blank
function isNotBlank(str) {
return (str && /^\s*$/.test(str));
}
All these answers are nice.
But I cannot be sure that variable is a string, doesn't contain 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.
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 === '')
...
I usually use something like:
if (str == "") {
//Do Something
}
else {
//Do Something Else
}
<html>
<head>
<script lang="javascript">
function nullcheck()
{
var n = "fdgdfg";
var e = n.length;
if (e == 0)
{
return true;
}
else
{
alert("success");
return false;
}
}
</script>
</head>
<body>
<button type="submit" value="add" onclick="nullcheck()"></button>
</body>
</html>
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.
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.
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());
}
Lots of useful information here, but in my opinion, one of the most important elements was not addressed.
null
, undefined
, and ""
are all falsy.
When evaluating for an empty string, it's often because you need to replace it with something else.
In which case, you can expect the following behavior.
var a = ""
var b = null
var c = undefined
console.log(a || "falsy string provided") // prints ->"falsy string provided"
console.log(b || "falsy string provided") // prints ->"falsy string provided"
console.log(c || "falsy string provided") // prints ->"falsy string provided"
With that in mind, a method or function that can return whether or not a string is ""
, null
, or undefined
(an invalid string) versus a valid string is as simple as this:
const validStr = (str) => str ? true : false
validStr(undefined) // returns false
validStr(null) // returns false
validStr("") // returns false
validStr("My String") // returns true
I hope that's helpful.
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
.
if ((str?.trim()?.length || 0) > 0) {
// str must not be any of:
// undefined
// null
// ""
// " " or just whitespace
}
Update: Since this answer is getting popular I thought I'd write a function form too:
const isNotNilOrWhitespace = input => (input?.trim()?.length || 0) > 0;
const isNilOrWhitespace = input => (input?.trim()?.length || 0) === 0;
Trimming whitespace with the null-coalescing operator:
if (!str?.trim()) {
// do something...
}
You can able to validate following ways and understand the difference.
var j = undefined;_x000D_
console.log((typeof j == 'undefined') ? "true":"false");_x000D_
var j = null; _x000D_
console.log((j == null) ? "true":"false");_x000D_
var j = "";_x000D_
console.log((!j) ? "true":"false");_x000D_
var j = "Hi";_x000D_
console.log((!j) ? "true":"false");
_x000D_
I use a combination, and the 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);
}
Starting with:
return (!value || value == undefined || value == "" || value.length == 0);
Looking at the last condition, if value == "", its length must be 0. Therefore drop it:
return (!value || value == undefined || value == "");
But wait! In JavaScript, an empty string is false. Therefore, drop value == "":
return (!value || value == undefined);
And !undefined is true, so that check isn't needed. So we have:
return (!value);
And we don't need parentheses:
return !value
Source: Stackoverflow.com