admin管理员组文章数量:1316688
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
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
-
1
const myString = 'result:' + [var1, ...arr1, var2].filter(s => s?.length ?? 0 > 0).join(' ');
– Aluan Haddad Commented Sep 9, 2020 at 8:32 -
1
@AluanHaddad Your solution looks really interesting but I don't understand it pletely. Could you please write it as an answer and explain why you use
s?
and??
and how they work? Thank you in advance. – winklerrr Commented Sep 9, 2020 at 8:48 -
1
It's called Optional chaining. My ment is almost exactly the same as @SpoonMeiser's answer, which I hadn't noticed.
s?.length
evaluates toundefined if
s` isundefined
ornull
, wheres.length
would throw.??
a fallback – Aluan Haddad Commented Sep 9, 2020 at 8:52 -
1
@AluanHaddad and that
0 > 0
part? – winklerrr Commented Sep 9, 2020 at 8:57 -
1
So, if
s
isnull
orundefined
thens?.length
will evaluate toundefined
Andundefined > 0
evaluates tofalse
(as doesundefined < 0
) sos?.length ?? 0
specifies that0
should be used as a fallback. The thought here is to treatnull
orundefined
values as if they were empty strings, filtering them out. – Aluan Haddad Commented Sep 9, 2020 at 9:02
3 Answers
Reset to default 5You 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);
Does this satisfy your requirements?
const strArr = ['result:' + var1, ...arr1, var2].map((a) => a.trim()).join(' ')
Update
As suggested, following handles
- empty string
- string with multiple spaces
- 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(' ')
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 + ' ' : '')
本文标签:
版权声明:本文标题:JavaScriptTypeScript: Concatenate string variables and string arrays with accordingly set spaces - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742005961a2411957.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论