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

155
Vistas
Split string by commas only not leaving whitespaces

Let's suggest I have the following string:
let cssValue = '20px, 40px'

I wish to get the following array after splitting:
cssValue.split(regex); // ['20px', '40px']

But if the string doesn't contain commas (spaces only, i.e. 20px 40px) the result should be ['20px 40px']

My regex [^a-zA-Z0-9]+ doesn't consider comma. With this regex I'm getting ['20px', '40px'] regardless of whether the string contains comma or not. How can I resolve it?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You could split by comma and possible whitespace directly.

const split = s => s.split(/,\s*/);

console.log(split('20px, 40px'));
console.log(split('20px 40px'));

about 4 years ago · Juan Pablo Isaza Denunciar

0

If you're only intending to split-by-comma and remove leading whitespace, you won't need to use a regex at all, if you don't want to.

The string ',' will suffice, since, if you want to tidy up any leading whitespace afterwards, you can use trim().


Working Example:

let cssValue1 = '20px, 40px';
let cssValue2 = '20px 40px';

const splitCSSValue = (cssValue) => cssValue.split(',');
const trimElements = (array) => array.map((element) => element.trim());

console.log(trimElements(splitCSSValue('20px, 40px')));
console.log(trimElements(splitCSSValue('20px 40px')));

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