Join strings with a delimiter only if strings are not null or empty

JavascriptString

Javascript Problem Overview


This feels like it should be simple, so sorry if I'm missing something here, but I'm trying to find a simple way to concatenate only non-null or non-empty strings.

I have several distinct address fields:

var address;
var city;
var state;
var zip;

The values for these get set based on some form fields in the page and some other js code.

I want to output the full address in a div, delimited by comma + space, so something like this:

$("#addressDiv").append(address + ", " + city + ", " + state + ", " + zip);

Problem is, one or all of these fields could be null/empty.

Is there any simple way to join all of the non-empty fields in this group of fields, without doing a check of the length of each individually before adding it to the string?

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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(', ');

Solution 3 - Javascript

Just:

[address, city, state, zip].filter(Boolean).join(', ');

Solution 4 - Javascript

Lodash solution: _.filter([address, city, state, zip]).join()

Solution 5 - Javascript

@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);

Solution 6 - Javascript

Try

function joinIfPresent(){
    return $.map(arguments, function(val){
        return val && val.length > 0 ? val : undefined;
    }).join(', ')
}
$("#addressDiv").append(joinIfPresent(address, city, state, zip));

Demo: Fiddle

Solution 7 - Javascript

$.each([address,city,state,zip], 
    function(i,v) { 
        if(v){
             var s = (i>0 ? ", ":"") + v;
             $("#addressDiv").append(s);
        } 
    }
);`

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionfroadieView Question on Stackoverflow
Solution 1 - JavascriptgeorgView Answer on Stackoverflow
Solution 2 - JavascriptagaView Answer on Stackoverflow
Solution 3 - JavascripttikhpavelView Answer on Stackoverflow
Solution 4 - JavascriptTim SantefordView Answer on Stackoverflow
Solution 5 - JavascriptAlexander AbakumovView Answer on Stackoverflow
Solution 6 - JavascriptArun P JohnyView Answer on Stackoverflow
Solution 7 - JavascriptnicbView Answer on Stackoverflow