Reputation: 14737
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.
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.
Is there a more elegant way to concatenate only the set variables separated with exactly one space?
Upvotes: 0
Views: 9758
Reputation: 2527
Does this satisfy your requirements?
const strArr = ['result:' + var1, ...arr1, var2].map((a) => a.trim()).join(' ')
Update
As suggested, following handles
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
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
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