I have this code:
var returnValue = item.fname + " " + item.mname + " " + item.lname
returnValue.replace(null," ");
return returnValue ;
Sometimes one of the fields is null so returnValue is:
"John null Doe"
or
"John something null"
I want to get rid of the "null" but my code does not seem to work.
Can someone help me out here?
Rather than replacing null afterwards, only append the individual names if they are not null.
var returnValue = "";
if (item.fname !== null) {
returnValue += item.fname + " ";
}
if (item.mname !== null) {
returnValue += item.mname + " ";
}
if (item.lname !== null) {
returnValue += item.lname;
}
return returnValue;
Alternatively, use Array.prototype.filter to remove nulls:
// store the names in an array
var names = [ item.fname, item.mname, item.lname ];
// filter the array to values where they are `!== null`
var notNullNames = names.filter(x => x !== null);
// join them with spaces
var returnValue = notNullNames.join(" ");
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