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

177
Views
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 answers
Answer question

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 Report

0

Try

const a = `one, two,

three`

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

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!