将长文本拆分为字符串数组

时间:2012-05-30 19:07:19

标签: javascript

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

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()的正则表达式,但我不知道怎么做..

3 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分: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"]

答案 2 :(得分:1)

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

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

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