在方法split返回的数组末尾获取空字符串

时间:2018-07-03 07:36:19

标签: javascript

var s = "Hello, how are you?";
var r = /([,\s?]+)/;
console.log(s.split(r));

为什么我在数组末尾得到一个空字符串?

2 个答案:

答案 0 :(得分:2)

删除\s之后的问号。

var s = "Hello, how are you?";
var r = /([,\s]+)/;
console.log(s.split(r));

答案 1 :(得分:1)

因为您也在对问号进行拆分。没有它:

var s = "Hello, how are you?";
var r = /([,\s]+)/;
console.log(s.split(r));
// including question mark in the split
// and empty values removed from the result
console.log(s.split(/([,\s]+|[?])/).filter(v => v.length));