Append commas only if strings are not null or empty in JavaScript
📅July 31, 2022
Today, we’ll show you how to append commas only if strings are not null or empty in JavaScript.
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.
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(", ");
console.log(output);
// 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(", ");
console.log(output);
// 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..!!