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

1
  • we may require this for our javascript programs later, not only angular typescript, so placing javascript tag Commented Dec 19, 2019 at 2:45

1 Answer 1

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(", ");
Sign up to request clarification or add additional context in comments.

3 Comments

The trim is done on each elements yes :) because it's inside the map() which iterates through each element and perform some action
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)
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.