javascript 在换行符和逗号上拆分字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34316090/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 17:32:58  来源:igfitidea点击:

Split string on newline and comma

javascriptangularjs

提问by Bidisha

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.

将来我需要在逗号和换行符上拆分什么应该是在逗号和换行符上拆分的正则表达式。我试过 - /, \n\ 但它不起作用。

回答by Merott

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. splittedis grammatically incorrect. Who cares if it's descriptive though?

pssplitted语法不正确。谁在乎它是否是描述性的?

回答by user5325596

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

您可以在拆分之前用逗号替换所有换行符。

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

回答by alek kowalczyk

Try

尝试

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

this regex should work.

这个正则表达式应该可以工作。