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));
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With