2

I have two strings which I want to concatenate using template literals. Second one is optional and I want to put it after comma (if exist). I know I can do something like this (but it doesn't look proper to me):

<div> {a} {b ? `, ${b}` : ''} </div> 
5
  • I can't think of a more proper way. Commented Feb 28, 2019 at 15:49
  • 1
    [a, b].filter(i => i).join(", ") - if you don't insist about literals Commented Feb 28, 2019 at 15:51
  • @Alex Would that be cleaner? Commented Feb 28, 2019 at 15:53
  • 1
    Yes and no, its relative to what you find to be more readable. And also on whether or not you are planning to add more variables later on Commented Feb 28, 2019 at 15:58
  • @Treycos I don't need to add more variables there and I'm looking here for the most proper way to do it Commented Feb 28, 2019 at 16:00

1 Answer 1

3

You can incapsulate logic to filter empty and joining into the component member (or util function), i.e.:

const concatNotEmptyBy = (separator) => (...args) => args .filter(n => n) // filter empty .join(separator); 

and next call it in your component:

<div> {concatNotEmptyBy(', ')(a, b)} </div> 

however, if it's only 1 place and only 2 variables then your original way is totally ok.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.