Hello, I was trying to check if a string is null or empty using javascript or jquery , just like we do in C#. Need one condition, which can check both the requirements at the same time and calls ajax if value is not null or empty.
Answered by:- vikas_jk
You can create a function which consider if value is not null or undefined
function CheckNullUndefined(value) {
return typeof value == 'string' && !value.trim() || typeof value == 'undefined' || value === null;
}
It can be used as below
CheckNullUndefined(undefined); //returns true
CheckNullUndefined(null); //returns true
CheckNullUndefined(''); //returns true
CheckNullUndefined('foo'); //returns false
CheckNullUndefined(1); //returns false
CheckNullUndefined(0); //returns false
OR
Simply call it like
if (!value.trim()) {
// is empty or whitespace
}
But, preferred method should be the first one as it checks whether to use .trim or not, checks null and undefined value perfectly.
OR
Simply use this
if(value !== null && value !== '')
{
//do something
}
Above will also do type equality check.
Answered by:- bhanu
You can also simply do this to check if string is null or empty as below
if (a == null || a=='')
{
//a is not null and empty
}
Thanks
You may like to read:
How to enable JavaScript debugging in visual studio 2019 or 2017
How do I clear local storage using javascript?
How to get query string from url using jQuery or Javascript?
Answered by:- pika
You can also simply use Dual NOT (!!) to check if string is empty or null
if (!!str) {
// if not null or empty code here
}
OR
you can also create your own function
function checkIfEmptyNull(e) {
switch (e) {
case "":
case 0:
case "0":
case null:
case false:
case undefined:
return true;
default:
return false;
}
}
checkIfEmptyNull(null) // true
checkIfEmptyNull(0) // true
checkIfEmptyNull(7) // false
checkIfEmptyNull("") // true
thanks
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly