Categories
JavaScript Answers

How to Join JavaScript Strings with a Delimiter Only if the Strings are not Null or Empty?

Spread the love

We can use the JavaScript array filter method to filter out all the null or empty strings first before joining them together with join .

For instance, we can write:

const address = "foo";
const city = '';
const state = "bar";
const zip = '';

const text = [address, city, state, zip].filter(Boolean).join(", ");
console.log(text)

We have an array of strings with some having empty strings as their value.

So we just call filter with Boolean to filter out the ones with an empty string as their value.

And then we call join to join the non-empty strings together with a comma.

Therefore, text is 'foo, bar’ .

We can also be more precise with our filtering by writing:

const address = "foo";
const city = '';
const state = "bar";
const zip = '';

const text = [address, city, state, zip]
  .filter(x => typeof x === 'string' && x.length > 0)
  .join(", ");
console.log(text)

We check if x is a string and if its length is longer than 0 to make sure filter returns array of non-empty strings.

Conclusion

We can use the JavaScript array filter method to filter out all the null or empty strings first before joining them together with join .

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *