Hoa*_*Hoa 111 javascript
如果我试试
"my, tags are, in here".split(" ,")
Run Code Online (Sandbox Code Playgroud)
我得到以下内容
[ 'my, tags are, in here' ]
Run Code Online (Sandbox Code Playgroud)
而我想要的
['my', 'tags', 'are', 'in', 'here']
Run Code Online (Sandbox Code Playgroud)
Jon*_*Jon 206
String.split
也可以接受正则表达式:
input.split(/[ ,]+/);
Run Code Online (Sandbox Code Playgroud)
该特定正则表达式在一个或多个逗号或空格的序列上分裂,使得例如多个连续空格或逗号+空格序列不在结果中产生空元素.
jon*_*ert 38
使用的建议.split(/[ ,]+/)
很好,但是迟早会使用自然句子,你最终会得到数组中的空元素.例如['foo', '', 'bar']
.
如果你的用例没问题,这很好.但是如果你想摆脱空元素你可以做:
var str = 'whatever your text is...';
str.split(/[ ,]+/).filter(Boolean);
Run Code Online (Sandbox Code Playgroud)
小智 26
你可以使用正则表达式来捕获任何长度的空白区域,这就像:
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"
Run Code Online (Sandbox Code Playgroud)
gab*_*ish 12
"my, tags are, in here".split(/[ ,]+/)
Run Code Online (Sandbox Code Playgroud)
结果是:
["my", "tags", "are", "in", "here"]
Run Code Online (Sandbox Code Playgroud)
input.split(/\s*[\s,]\s*/)
...\s*
匹配零个或多个空白字符(不仅是空格,还有制表符和换行符)。
...[\s,]
匹配一个空格字符或一个逗号
归档时间: |
|
查看次数: |
115185 次 |
最近记录: |