1

我需要使用正则表达式将一个字符串分成两部分,所以我使用了以下代码:

var str = "This is a test";
var list = str.split(/(test)/);

所需输出:

list = ["This is a ", "test"]

而不是 2 这给了我数组中的 3 个元素(最后一个是空的)。我知道正则表达式在第二次匹配之后什么也没找到,所以它添加了一个空(第三个)元素。有什么办法可以修改我的代码,这样我就可以得到两个元素,从而避免最后一个空元素?

注意:上面的代码是一个简化版本,我们可以使用除正则表达式之外的其他选项,但我必须使用正则表达式。

4

4 回答 4

1
var str = "This is a test";

var list = str.split(/(test)/,2);

列表: ["This is a ", "test"]

于 2013-09-10T13:30:31.387 回答
1

Perhaps overkill if you can guarantee that you are only expecting an array of length two but given the nature of the question a more robust solution may be to use Array.filter to remove all empty strings from the array - including entries in the middle of the array which would arise from several delimiters appearing next to each other in your input string.

var list = str.split(/(test)/).filter(
    function(v){ return v!=null && v!='' }
);
于 2013-09-10T14:19:51.417 回答
0

您可以尝试检查最后一个元素是否为空:

var last = list.pop();
    last.length || list.push(last);

或者:

list[list.length-1].length || list.pop();

甚至更短:

list.slice(-1)[0].length || list.pop();

要处理第一个空元素(test was there如@Kobi 建议的那样),请使用:

list[0].length || list.shift();
于 2013-09-10T13:04:25.177 回答
0

这给了我你想要的结果:

var str = "This is a test";
var list = str.split(/(?=test)/g);

(?= is a lookahead, it doesn't capture the word test so that stays in the array after splitting.

于 2013-09-10T14:19:02.850 回答