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?

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

Comments

16

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

$scope.memberList.replace(/\n/g, ",").split(",")

4 Comments

This would only match the first occurrence of a new line. You'd have to do .replace(/\n/g, ",") to replace all occurrences
@Merott - excellent point
Thanks that wud also work !!
It should actually be .replace(/\r?\n/g, ",") to handle both unix/mac and windows new lines.
7

Try

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

this regex should work.

1 Comment

Yes that wud work but need atleast one or more comma or new line

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.