0

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

  • we may require this for our javascript programs later, not only angular typescript, so placing javascript tag –  Dec 19 '19 at 02:45

1 Answers1

0

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(", ");
freedomn-m
  • 27,664
  • 8
  • 35
  • 57
Jojofoulk
  • 2,127
  • 1
  • 7
  • 25
  • The trim is done on each elements yes :) because it's inside the `map()` which iterates through each element and perform some action – Jojofoulk Dec 19 '19 at 02:50
  • You can change `elem=>elem.replace(/\s+/g, ' ').trim()` to `elem=>elem && elem.replace(/\s+/g, ' ').trim()` in the map function, this will make sure you only replace white spaces for truthy elements in the array (so not null or undefined) – Jojofoulk Dec 19 '19 at 03:20
  • Works too, keeping them in the map could be useful if you wanted to do something specific for falsy values (like displaying a certain string, or logging something), but in your case, filtering first makes more sense – Jojofoulk Dec 19 '19 at 03:24