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.

1

3 Answers 3

22

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?

16

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

$scope.memberList.replace(/\n/g, ",").split(",")
4
  • This would only match the first occurrence of a new line. You'd have to do .replace(/\n/g, ",") to replace all occurrences
    – Merott
    Commented Dec 16, 2015 at 15:47
  • @Merott - excellent point Commented Dec 16, 2015 at 15:49
  • Thanks that wud also work !!
    – Bidisha
    Commented Dec 16, 2015 at 15:57
  • It should actually be .replace(/\r?\n/g, ",") to handle both unix/mac and windows new lines. Commented Jun 19, 2021 at 4:32
7

Try

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

this regex should work.

1
  • Yes that wud work but need atleast one or more comma or new line
    – Bidisha
    Commented Dec 16, 2015 at 15:58

Not the answer you're looking for? Browse other questions tagged or ask your own question.