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:
- I need to combine all the words- Join strings with a delimiter only if strings are not null or empty
- Remove Middle Multiple White Spaces- Replace multiple whitespaces with single whitespace in JavaScript string
- Also Totally Remove Leading and Trailing Spaces from each Individual word.
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