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
0
: 134 At:- 12/24/2019 11:05:37 AM
Javascript jQuery string is null or empty using javascript






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

1
At:- 12/26/2019 10:27:11 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

Subscribe Now

Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly