如何用空格或逗号分割 JavaScript 字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10346722/
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
How can I split a JavaScript string by white space or comma?
提问by Hoa
If I try
如果我尝试
"my, tags are, in here".split(" ,")
I get the following
我得到以下
[ 'my, tags are, in here' ]
Whereas I want
而我想要
['my', 'tags', 'are', 'in', 'here']
回答by Jon
String.split
can also accept a regular expression:
String.split
也可以接受正则表达式:
input.split(/[ ,]+/);
This particular regex splits on a sequence of one or more commas or spaces, so that e.g. multiple consecutive spaces or a comma+space sequence do not produce empty elements in the results.
这个特定的正则表达式在一个或多个逗号或空格的序列上拆分,因此例如多个连续空格或逗号+空格序列不会在结果中产生空元素。
回答by jonschlinkert
The suggestion to use .split(/[ ,]+/)
is good, but with natural sentences sooner or later you'll end up getting empty elements in the array. e.g. ['foo', '', 'bar']
.
使用的建议.split(/[ ,]+/)
很好,但是对于自然句子,您迟早会在数组中获得空元素。例如['foo', '', 'bar']
。
Which is fine if that's okay for your use case. But if you want to get rid of the empty elements you can do:
如果这对您的用例没问题,那很好。但是如果你想摆脱空元素,你可以这样做:
var str = 'whatever your text is...';
str.split(/[ ,]+/).filter(Boolean);
回答by Cemil Dogan
you can use regex in order to catch any length of white space, and this would be like:
您可以使用正则表达式来捕获任何长度的空格,这将类似于:
var text = "hoi how are you";
var arr = text.split(/\s+/);
console.log(arr) // will result : ["hoi", "how", "are", "you"]
console.log(arr[2]) // will result : "are"
回答by gabitzish
"my, tags are, in here".split(/[ ,]+/)
the result is :
结果是:
["my", "tags", "are", "in", "here"]
回答by KaptajnKold
input.split(/\s*[\s,]\s*/)
input.split(/\s*[\s,]\s*/)
… \s*
matches zero or more white space characters (not just spaces, but also tabs and newlines).
...\s*
匹配零个或多个空白字符(不仅是空格,还有制表符和换行符)。
... [\s,]
matches one white space character or one comma
...[\s,]
匹配一个空格字符或一个逗号
If you want to avoid blank elements from input like "foo,bar,,foobar"
, this will do the trick:
如果您想避免输入中的空白元素,例如"foo,bar,,foobar"
,这可以解决问题:
input.split(/(\s*,?\s*)+/)
input.split(/(\s*,?\s*)+/)
The +
matches one or more of the preceding character or group.
所述+
匹配的一个或多个前面的字符或基团。
Edit:
编辑:
Added ?
after comma which matches zero or one comma.
?
在匹配零个或一个逗号的逗号之后添加。
Edit 2:
编辑2:
Turns out edit 1 was a mistake. Fixed it. Now there has to be at least one comma or one space for the expression to find a match.
原来编辑1是一个错误。修复。现在,表达式必须至少有一个逗号或一个空格才能找到匹配项。
回答by grantwparks
When I want to take into account extra characters like your commas (in my case each token may be entered with quotes), I'd do a string.replace() to change the other delimiters to blanks and then split on whitespace.
当我想考虑像逗号这样的额外字符(在我的情况下,每个标记都可以用引号输入)时,我会执行 string.replace() 将其他分隔符更改为空格,然后在空格上拆分。