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.
Checkout more articles on JavaScript
- Verify an image URL in JavaScript
- Methods of Promises in JavaScript
- Get the day name of date using JavaScript
- How to merge arrays in JavaScript
- Convert a 12 hour format to 24 hour format using JavaScript
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(", ");
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..!! 🙂