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

179
Vistas
How to use regex to split a string by comma or linebreak in javascript?

I have a React application where I need to split user input (string) by either comma or linebreak to later map them out as a list. Each one work individually, but when I have 2 different examples on the page only one of them work and the other one is read as one string. Input can look like:

one, two, three

or like:

one 
two  
three

I've tried:

const foo = ((',') || (/[\r\n]+/)); 

.split(foo)

But only one of them works then.

.split(',') works and .split('\n') also works (as well as more complex regex like (/[\r\n]+/) .

How do I add that it should be either comma or linebreak (for both windows and unix) to split on?

Help much appreciated!

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

0

const str1 = 'one, two, three';

const str2 = `foo
bar
baz`;

const str3 = `1,2,3
a,b,c
foo,bar,baz`;

const re = /, ?|\n/gm;
//          ^ matches a comma (`,`)
//           ^^ optionally followed by a space (` ?`) [remove this bit, if you do not need it]
//             ^ OR (`|`)
//              ^^ a new line (`\n`)

// test
console.log(str1.split(re));
console.log(str2.split(re));
console.log(str3.split(re));

about 4 years ago · Juan Pablo Isaza Denunciar

0

Try

const a = `one, two,

three`

a.split(/[\s,]/g).filter(string => Boolean(string))

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