2

I was wondering what is the best way to join a few strings in javascript except if they are empty.

Say we have

let s1 = 'X = 1';
let s2 = '';
let s3 = 'Z = 3';

And my end result need to be "X = 1, Z = 3"

let str = [s1,s2,s3].join(',')  // will have extra comma

let str = [s1!??' , ' ,s2!??' , ' ,s3].join(' ')  //is ugly, and will not work

let str = [u1&&',' ,u2&&',',u3].join('')  //close, but no cigar.

But I am sure there must be an elegant way to do this join!

And someone here on stackoverflow will point me in the right direction.

4
  • 3
    Use .filter() to create a new array without empty strings, and then .join() that. Commented Feb 24, 2022 at 14:55
  • 1
    Thanks.let str = [u1,u2,u3].filter(e => e.length).join(','); works 100%. Commented Feb 24, 2022 at 15:13
  • .filter(Boolean) will also work since an empty string is falsey value. Also, comma is default delimiter for .join() if you really wanna code golf it. Commented Feb 24, 2022 at 20:11
  • @Clothahump I added an answer. Did you get a chance to look into that. Hope it will work as per your expectation. Commented Mar 1, 2022 at 5:58

2 Answers 2

5

You can use .filter(Boolean) (which is the same as .filter(x => x)) removes all falsy values (null, undefined, empty strings etc...)

Working Demo :

let s1 = 'X = 1';
let s2 = '';
let s3 = 'Z = 3';

let str = [s1,s2,s3].filter(Boolean).join(", ");

console.log(str);

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

Comments

0

You can also achieve the same using the code below. Filter Boolean eliminates all falsey values like undefined, empty strings, null etc

  let str = [u1,u2,u3].filter(Boolean).join(',');

1 Comment

Some comments describing this would be helpful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.