Reputation:
The following will concatenate multiple words and removes all "falsy" values (nulls, undefineds, empty strings etc).
combinedAddress = [address, city, state, zip].filter(Boolean).join(", ");
Additionally, this will remove all middle Multiple white spaces in a single space.
city.replace(/\s+/g, ' ')
Goal:
The final result is below. Just curious if there is any way to simplify this, or is this optimal practice syntax? We are using Angular 8 Typescript (subset of Javascript).
combinedAddress = [address.replace(/\s+/g, ' ').trim(), city.replace(/\s+/g, ' ').trim(), state.replace(/\s+/g, ' ').trim(), zip.replace(/\s+/g, ' ').trim()].filter(Boolean).join(", ");
Join strings with a delimiter only if strings are not null or empty
Replace multiple whitespaces with single whitespace in JavaScript string
Upvotes: 0
Views: 3549
Reputation: 2216
you can have it as a one-liner with something like:
combinedAddress = [address, city, state, zip].map(elem=>elem.replace(/\s+/g, ' ').trim()).filter(Boolean).join(", ");
Although sometime temp variable are clearer:
let addresses = [address, city, state, zip];
let combinedAddress = addresses.map(elem=>elem.replace(/\s+/g, ' ').trim());
let truthyAddresses = combinedAddress .filter(Boolean).join(", ");
Upvotes: 0