Home > database >  Joining strings except empty ones in javascript
Joining strings except empty ones in javascript

Time:02-27

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.

CodePudding user response:

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

CodePudding user response:

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