Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

161
Views
Joining strings except empty ones in javascript

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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

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(',');
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!