Join strings with a comma only if strings are not null or empty
Today, we’ll show you how to join strings with a comma only if strings are not null or empty.
Here, we will use the join Array method with comma delimiter to concat the strings. But we will also add one more check to filter the empty or null records.
In this article, we will try to combine the following strings with a comma delimiter.
const addressLine1 = "Address Line 1";
const addressLine2 = "";
const city = "City";
const state = "State";
const postcode = null;
const country = "Country";
Join strings using a comma
Let’s combine the above strings using the
join() method and check the output log.
const output = [addressLine1, addressLine2, city, state, postcode, country].join(", ");
// Address Line 1, , City, State, , Country
You may have noticed that we have multiple commas next to each other when values are empty or null. So use the following code to avoid it.
const output = [addressLine1, addressLine2, city, state, postcode, country].filter(Boolean).join(", ");
// Address Line 1, City, State, Country
In the above code, we have used the
.filter(Boolean) (which is the same as
.filter(x => x)) to remove all
falsy values (null, undefined, empty strings etc).
I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂