如何用空格或逗号分割字符串?
2022-08-30 03:07:38
如果我尝试
"my, tags are, in here".split(" ,")
我得到以下
[ 'my, tags are, in here' ]
而我想要
['my', 'tags', 'are', 'in', 'here']
如果我尝试
"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"