winklerrr
winklerrr

Reputation: 14737

JavaScript/TypeScript: Concatenate string variables and string arrays with accordingly set spaces

Situation

I want to concatenate string variables and string arrays in TypeScript like in this simple example:

// var1, var2: string
// arr1: string[]
const myString = 'result:' + var1 + ' ' + arr1.join(' ') + ' ' var2;

I don't want multiple spaces concatenated together and there shouldn't be any spaces at the end.

Problem

It is possible that those variables are set to '' or that the array is empty. These leads to multiple spaces concatenated together which I want to avoid.

Question

Is there a more elegant way to concatenate only the set variables separated with exactly one space?

Conditions

Upvotes: 0

Views: 9758

Answers (3)

Pritam Kadam
Pritam Kadam

Reputation: 2527

Does this satisfy your requirements?

const strArr = ['result:' + var1, ...arr1, var2].map((a) => a.trim()).join(' ')

Update

As suggested, following handles

  1. empty string
  2. string with multiple spaces
  3. trim additional spaces
const strArr = ['result:' + var1, ...arr1, var2].map((a) => a.trim()).filter(Boolean).join(' ')

Update 2

If you are using ES2019, you could do this in single pass:

const strArr = 
['result:' + var1, ...arr1, var2]
         .flatMap((el) => Boolean(el.trim()) ? [el.trim()] :[]).join(' ')

Upvotes: 1

SpoonMeiser
SpoonMeiser

Reputation: 20417

You can use destructuring to concatenate everything into a temporary array, and then use filter to remove any empty elements before calling join on the lot.

let var1 = "var1";
let arr1 = ["one", "", "two"];
let var2 = ""

const myString = "result:" + [var1, ...arr1, var2].filter(s => s).join(' ');

console.log(myString);

Upvotes: 4

Robert Kossendey
Robert Kossendey

Reputation: 6998

You could try this: const cleanedResult = result.replace(/\s\s+/g, ' ').trim()

This would remove multiple spaces in your variables as well though.

If you do not want that you can try out this solution:

const result = 'result:' + (var1 ? var1 + ' ' : '')  + (arr1 ? arr1.join(' ') : '') + (var2 ? var2 + ' ' : '')

Upvotes: 0

Related Questions