Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove "null" from string in javascript

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?

like image 259
hacking_mike Avatar asked Sep 10 '26 14:09

hacking_mike


1 Answers

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(" ");
like image 52
James Monger Avatar answered Sep 12 '26 03:09

James Monger