Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript generic isBlank function

Tags:

javascript

I am working on a generic isBlank function in JS like Java StringUtils.isBlank();
I would like your opinion on the implementation in case I missed something like == vs === or better implementation?
so the following are considerd blank:

var a;         //undefined => true
var b = null;  //null            => true
var c = '';    //emptyString     => true
var d = '  ';   //emptyString    => true
var e = ' \b \f \n \r \t \v \0 ';   //emptyString with other white space => true

Implementation:

    function isBlank(value){      
        return(value == undefined || value == null || value.trim() == '');
    }

var a;         //undefined => true
var b = null;  //null			 => true
var c = '';	   //emptyString	 => true
var d = '  ';   //emptyString	 => true
var d1 = ' \b \f \n \r \t \v \0 ';
var e = 'X';    //char	 => false
var f = '#';   //char	 => false
var g = '1';   //digit	 => false



		function isBlank(value){      
			return(value == undefined || value == null || value.trim() == '');
		}

console.log('a => ' + isBlank(a));
console.log('b => ' + isBlank(b));
console.log('c => ' + isBlank(c));
console.log('d => ' + isBlank(d));
console.log('d1 => ' + isBlank(d1));
console.log('e => ' + isBlank(e));
console.log('f => ' + isBlank(f));
console.log('g => ' + isBlank(g));
like image 933
JavaSheriff Avatar asked Mar 06 '26 11:03

JavaSheriff


1 Answers

You can shorten your function by using ! operator which will convert both undefined and null to true (since it negates falsy values):

var a;         //undefined => true
var b = null;  //null			 => true
var c = '';	   //emptyString	 => true
var d = '  ';   //emptyString	 => true
var e = 'X';    //char	 => false
var f = '#';   //char	 => false
var g = '1';   //digit	 => false
var h = 1;   //digit	 => false
var d1 = ' \b \f \n \r \t \v \0 '; // whitespaces => true
var d2 = ' \b \f \n aa \r \t \v \0 '; // whitespaces with regular text => false

function isBlank(value){      
   return !value || !value.toString().trim() || /^[\s\b\0]+$/.test(value.toString());
}

console.log('a => ' + isBlank(a));
console.log('b => ' + isBlank(b));
console.log('c => ' + isBlank(c));
console.log('d => ' + isBlank(d));
console.log('e => ' + isBlank(e));
console.log('f => ' + isBlank(f));
console.log('g => ' + isBlank(g));
console.log('h => ' + isBlank(h));
console.log('h => ' + isBlank(d1));
console.log('h => ' + isBlank(d2));

EDIT: added isBlank2 to support numbers if needed

like image 87
mickl Avatar answered Mar 08 '26 00:03

mickl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!