Stephen K
Stephen K

Reputation: 737

Accept either comma separated values or newline separated values

I have this code:

var skus = !input.match(/\,/) ? input.split('\n') : input.split(',');

This will get the contents of a <textarea> and depending on whether or not it contains commas, will return an array of items split by \n or ,. I don't believe this to be the best way to do it.

Before I just had :

var skus = input.split('\n') || input.split(',')

which was not giving me the result I wanted/expected. Is there a method/function/trick to accept either a list of CSV or new line separated values and split them by whichever the delimiter is?

Upvotes: 0

Views: 533

Answers (1)

Matt Berkowitz
Matt Berkowitz

Reputation: 975

You can use a regex in the split, like so:

'1,2\n3'.split(/[,\n]/)

Upvotes: 1

Related Questions