how to check if string is null or empty using jQuery or javascript?


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.


Asked by:- neena
2
: 9682 At:- 12/24/2019 11:05:37 AM
Javascript jQuery string is null or empty using javascript







3 Answers
profileImage 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.

2
At:- 12/26/2019 10:27:11 AM Updated at:- 9/20/2022 12:53:08 AM


profileImage 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?

1
At:- 5/26/2021 11:23:26 AM Updated at:- 5/26/2021 11:26:47 AM


profileImage 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

1
At:- 6/3/2022 8:00:32 AM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use