Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

165
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda