1

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.

philipxy
  • 14,867
  • 6
  • 39
  • 83
Clothahump
  • 47
  • 5
  • 3
    Use `.filter()` to create a new array without empty strings, and then `.join()` that. – Pointy Feb 24 '22 at 14:55
  • 1
    Thanks.```let str = [u1,u2,u3].filter(e => e.length).join(',');``` works 100%. – Clothahump Feb 24 '22 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. – CrayonViolent Feb 24 '22 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. – Debug Diva Mar 01 '22 at 05:58

2 Answers2

4

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);
Debug Diva
  • 26,058
  • 13
  • 70
  • 123
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(',');
dennohpeter
  • 391
  • 4
  • 16