2

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!

3
  • 1
    I think the RegExp yu are looking for is /, |\n/gm (see: jsfiddle.net/8xvjr2gt). Please notice that RegExp would split by comma + space or new line; if you want to split only by comma or new line, you can modify it to /,|\n/gm (but, in this case, your first sample string would be split into ['one', ' two', ' three'], with a space before the second and third elements) Commented Aug 13, 2021 at 15:23
  • This worked like a charm, thank you very much! Yes, normally I assume comma + space is what is required, but in this case another app takes with after the mapping and sorts that out but, it's still a nice bonus and may help others, too. Commented Aug 13, 2021 at 16:11
  • If you want to treat multiple consecutive newlines and comma's as a single split you can add it to the character class [,\r\n]+ See regex101.com/r/25QSFV/1 Commented Aug 13, 2021 at 22:25

2 Answers 2

1

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));

Sign up to request clarification or add additional context in comments.

Comments

0

Try

const a = `one, two,

three`

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.