14

My input String is like

abc,def,wer,str

Currently its splitting only on comma but in future it will contain both comma and newline. Current code as below:

$scope.memArray = $scope.memberList.split(",");

In future I need to split on both comma and newline what should be the regex to split both on comma and newline. I tried - /,\n\ but its not working.

Bidisha
  • 287
  • 1
  • 5
  • 16
  • 2
    look at this http://stackoverflow.com/questions/650022/how-do-i-split-a-string-with-multiple-separators-in-javascript – RaniDevpr Dec 16 '15 at 15:43

3 Answers3

20

You can use a regex:

var splitted = "a\nb,c,d,e\nf".split(/[\n,]/);
document.write(JSON.stringify(splitted));

Explanation: [...] defines a "character class", which means any character from those in the brackets.

p.s. splitted is grammatically incorrect. Who cares if it's descriptive though?

Selfish
  • 6,023
  • 4
  • 44
  • 63
Merott
  • 7,189
  • 6
  • 40
  • 52
16

You could replace all the newlines with a comma before splitting.

$scope.memberList.replace(/\n/g, ",").split(",")
user5325596
  • 2,310
  • 4
  • 25
  • 42
7

Try

.split(/[\n,]+/)

this regex should work.

alek kowalczyk
  • 4,896
  • 1
  • 26
  • 55