我需要一种方法将一个字符串拆分成一个较小的字符串数组,按字数拆分。是的,我正在寻找这样的功能:
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() 的正则表达式,但我不知道该怎么做......
最佳答案
首先用空格分割,然后将数组分块。
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;
}
关于javascript - 将长文本拆分为字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10822647/