Reputation: 15912
I need a method to split a string into an array of smaller strings, spliting it by word count. It is, I'm looking for a function like that:
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);
In this case, cut should return 4 arrays with 3 words each. I've tried to figure out a regex for String.match() or String.split(), but I don't know how to do it..
Upvotes: 1
Views: 2173
Reputation: 214949
Make a function that splits an array into chunks:
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;
}
and apply this function to the list of words:
var str = "word1 word2 word3 word4 word5 word6 word7 word8 word9 word10 word11";
chunk(str.match(/\w+/g), 3)
str.match(/\w+/g)
can be also str.split(/\s+/)
depending on how you want to handle non-word characters.
If you only interested to create an array of substrings (and not arrays of words as the question states), here's a solution that doesn't leave trailing spaces in substrings:
str.match(new RegExp("(\\S+\\s+){1," + (num - 1) + "}\\S+", "g"))
returns
["word1 word2 word3", "word4 word5 word6", "word7 word8 word9", "word10 word11 word12"]
Upvotes: 1
Reputation: 1227
Let's do something crazy:
function cut(str, num){
return str.match(new RegExp("(?:(?:^|\\s)\\S+){1," + num + "}", "g"));
}
This creates a new RegExp at every run and matches the string. There are probably better solutions in terms of speed, but this is wonderful Mad Science(TM). And it's short.
Upvotes: 1
Reputation: 324620
First split it by spaces, then chunk the array together.
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;
}
Upvotes: 2