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!
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));
Try
const a = `one, two,
three`
a.split(/[\s,]/g).filter(string => Boolean(string))