[英]How to split a string by white space or comma?
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']
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 eg multiple consecutive spaces or a comma+space sequence do not produce empty elements in the results.这个特定的正则表达式在一个或多个逗号或空格的序列上拆分,因此例如多个连续空格或逗号+空格序列不会在结果中产生空元素。
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"
The suggestion to use .split(/[ ,]+/)
is good, but with natural sentences sooner or later you'll end up getting empty elements in the array.使用
.split(/[ ,]+/)
的建议很好,但是对于自然句子,迟早你会在数组中得到空元素。 eg ['foo', '', 'bar']
.例如
['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);
"my, tags are, in here".split(/[ ,]+/)
结果是:
["my", "tags", "are", "in", "here"]
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,]
匹配一个空格字符或一个逗号
当我想考虑像逗号这样的额外字符(在我的情况下,每个标记都可以用引号输入)时,我会执行 string.replace() 将其他分隔符更改为空格,然后在空格上拆分。
When you need to split a string with some single char delimiters, consider using a reverse logic: match chunks of strings that consist of chars other than the delimiter chars.当您需要使用某些单个字符分隔符拆分字符串时,请考虑使用反向逻辑:匹配由除分隔符字符以外的字符组成的字符串块。
So, to extract all chunks of chars other than whitespace (matched with \\s
) and commas, you can use因此,要提取除空格(与
\\s
匹配)和逗号以外的所有字符块,您可以使用
console.log("my, tags are, in here".match(/[^\\s,]+/g)) // => ["my","tags","are","in","here"]
See the regex demo .请参阅正则表达式演示。
String#match
extracts all non-overlapping occurrences of one or more ( +
) chars other than whitespace and comma ( [^\\s,]
). String#match
提取除空格和逗号 ( [^\\s,]
) 之外的一个或多个 ( +
) 字符的所有非重叠出现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.