user12555362
user12555362

Reputation:

javascript - Join Strings, Remove Middle Multiple Spaces, and Trim Each Word

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:

  1. I need to combine all the words- Join strings with a delimiter only if strings are not null or empty
  2. Remove Middle Multiple White Spaces- Replace multiple whitespaces with single whitespace in JavaScript string
  3. 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

Upvotes: 0

Views: 3549

Answers (1)

JossFD
JossFD

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

Related Questions