TransWikia.com

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

Stack Overflow Asked by winklerrr on January 8, 2021

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

  • The solution should work with more variables/arrays
  • The solution should be a one-liner

3 Answers

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);

Correct answer by SpoonMeiser on January 8, 2021

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(' ')

Answered by Pritam Kadam on January 8, 2021

You could try this: const cleanedResult = result.replace(/ss+/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 + ' ' : '')

Answered by Robert Kossendey on January 8, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP