Joining multiple Strings into one comma-separated String
Nirmal Patel
Posted on July 22, 2020
One of the mobile apps I work on displays the user's address.
The API returns the address split across multiple fields in the following format:
let address = {
addressLine1: 'xxx',
addressLine2: 'yyy',
city: 'zzz',
state: 'AA',
zipcode: 'ddddd'
}
The caveat here is that one or more fields could be null/blank depending on what data was entered by the user at time of creating the address.
However, when displaying on the screen we want to ignore any blanks and show a consistent comma-separated string.
let array = [
address.addressLine1,
address.addressLine2,
address.city,
address.state,
address.zipcode
];
return array.filter(function(val) {
return val;
}).join(', ');
.filter()
removes any falsy strings - both blanks, nulls.
.join()
takes care of adding a ,
only when needed to join multiple strings.
💖 💪 🙅 🚩
Nirmal Patel
Posted on July 22, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
webdev A Tale of WeakMap and WeakSet in JavaScript: The Guardians of Forgotten Secrets
November 29, 2024