1

我需要一种将字符串拆分为较小字符串数组的方法,并按字数进行拆分。是的,我正在寻找这样的功能:

function cut(long_string, number_of_words) { ... }

var str = "word1 word2 word3 word4 word5 word6 word7 word8 word9 word10 word11 word12";
var arr = cut(str, 3);

在这种情况下,cut 应该返回 4 个数组,每个数组包含 3 个单词。我试图找出 String.match() 或 String.split() 的正则表达式,但我不知道该怎么做..

4

3 回答 3

2

首先用空格分割它,然后将数组分块在一起。

function cut(input,words) {
    input = input.split(" ");
    var l = input.length, i, ret = [];
    for( i=0; i<l; i+=words) {
        ret.push(input.splice(0,words));
    }
    return ret;
}
于 2012-05-30T19:11:44.917 回答
1

创建一个将数组拆分为块的函数:

chunk = function(ary, len) {
    var i = 0, res = [];
    for (var i = 0; i < ary.length; i += len)
        res.push(ary.slice(i, i + len));
    return res;
}

并将此函数应用于单词列表:

var str = "word1 word2 word3 word4 word5 word6 word7 word8 word9 word10 word11";
chunk(str.match(/\w+/g), 3)

str.match(/\w+/g)也可以str.split(/\s+/)取决于您要如何处理非单词字符。

如果您只对创建子字符串数组(而不是问题所述的单词数组)感兴趣,这里有一个不会在子字符串中留下尾随空格的解决方案:

str.match(new RegExp("(\\S+\\s+){1," + (num - 1) + "}\\S+", "g"))

返回

["word1 word2 word3", "word4 word5 word6", "word7 word8 word9", "word10 word11 word12"]
于 2012-05-30T19:15:43.450 回答
1

让我们做一些疯狂的事情:

function cut(str, num){
    return str.match(new RegExp("(?:(?:^|\\s)\\S+){1," + num + "}", "g"));
}

这会在每次运行时创建一个新的 RegExp 并匹配字符串。在速度方面可能有更好的解决方案,但这是很棒的Mad Science(TM)。而且很短。

于 2012-05-30T19:27:22.447 回答