Join strings with a delimiter only if strings are not null or empty
Consider
var address = "foo";
var city;
var state = "bar";
var zip;
text = [address, city, state, zip].filter(Boolean).join(", ");
console.log(text)
.filter(Boolean)
(which is the same as .filter(x => x)
) removes all "falsy" values (nulls, undefineds, empty strings etc). If your definition of "empty" is different, then you'll have to provide it, for example:
[...].filter(x => typeof x === 'string' && x.length > 0)
will only keep non-empty strings in the list.
--
(obsolete jquery answer)
var address = "foo";
var city;
var state = "bar";
var zip;
text = $.grep([address, city, state, zip], Boolean).join(", "); // foo, bar
Yet another one-line solution, which doesn't require jQuery
:
var address = "foo";
var city;
var state = "bar";
var zip;
text = [address, city, state, zip].filter(function (val) {return val;}).join(', ');
Just:
[address, city, state, zip].filter(Boolean).join(', ');
Lodash solution: _.filter([address, city, state, zip]).join()