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()
@aga's solution is great, but it doesn't work in older browsers like IE8 due to the lack of Array.prototype.filter() in their JavaScript engines.
For those who are interested in an efficient solution working in a wide range of browsers (including IE 5.5 - 8) and which doesn't require jQuery, see below:
var join = function (separator /*, strings */) {
// Do not use:
// var args = Array.prototype.slice.call(arguments, 1);
// since it prevents optimizations in JavaScript engines (V8 for example).
// (See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments)
// So we construct a new array by iterating through the arguments object
var argsLength = arguments.length,
strings = [];
// Iterate through the arguments object skipping separator arg
for (var i = 1, j = 0; i < argsLength; ++i) {
var arg = arguments[i];
// Filter undefineds, nulls, empty strings, 0s
if (arg) {
strings[j++] = arg;
}
}
return strings.join(separator);
};
It includes some performance optimizations described on MDN here.
And here is a usage example:
var fullAddress = join(', ', address, city, state, zip);
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