如何用空格或逗号拆分字符串
How to split a string by white space or comma?
如果我尝试
"my, tags are, in here".split(" ,")
我得到以下内容
[ 'my, tags are, in here' ]
而我想要
['my', 'tags', 'are', 'in', 'here']
String.split()
也可以接受正则表达式:
input.split(/[ ,]+/);
这个特定的正则表达式在一个或多个逗号或空格的序列上拆分,因此例如多个连续空格或逗号+空格序列不会在结果中产生空元素。
您可以使用正则表达式来捕获任意长度的空格,如下所示:
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"
使用.split(/[ ,]+/)
的建议很好,但是对于自然句子,您迟早会在数组中获得空元素。 例如 ['foo', '', 'bar']
.
如果这对您的用例没问题,那很好。但是如果你想摆脱空元素,你可以这样做:
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*
匹配零个或多个空格字符(不仅是空格,还包括制表符和换行符)。
。 ['s,]
匹配一个空格字符或一个逗号
当我想考虑逗号等额外字符时(在我的情况下,每个标记都可以用引号输入),我会做一个 string.replace() 将其他分隔符更改为空白,然后在空格上拆分。
当您需要使用一些单字符分隔符拆分字符串时,请考虑使用反向逻辑:匹配由分隔符字符以外的字符组成的字符串块。
因此,要提取除空格(与's
匹配)和逗号以外的所有字符块,您可以使用
console.log("my, tags are, in here".match(/[^'s,]+/g))
// => ["my","tags","are","in","here"]
请参阅正则表达式演示。 String#match
提取除空格和逗号([^'s,]
之外的一个或多个(+
)字符的所有非重叠匹配项。
相关文章:
- 通过跳过拆分字符在 javascript 中拆分字符串
- jQuery字符串使用split()方法在空格后拆分字符串
- Javascript-正则表达式,用于在未转义字符上拆分字符串,例如|,但忽略|
- 如何在JavaScript中按大小写拆分字符串
- 根据上次出现的、和_拆分字符串
- 拆分字符串数组(JavaScript)后未定义
- 在空行上拆分字符串
- 使用Regex拆分字符串,保留分隔符
- 使用jquery或regex,带点但不带点的拆分字符串位于单引号中
- Nashorn和Rhino:使用空白regexp拆分字符串
- Javascript:不使用.split()方法拆分字符串
- 如何使用正则表达式在javascript中拆分字符串
- Javascript在第一个空格上拆分字符串
- 首次出现时拆分字符串
- 如何使用正则表达式(.match())拆分字符串
- 使用正则表达式拆分字符串
- Javascript:拆分字符串,但仅使用 1 个结果
- Angularjs-拆分字符串问题
- angularjs在拆分字符串时解析语法错误
- 基于javascript中的AND OR逻辑拆分字符串